Socket.io failing to log chat message in console - node.js

I'm walking through the Socket.io tutorial on creating a chat room, and I'm having trouble getting my app to log the chat message to the console.
The app is logging when a user connects & disconnects, but it is not logging when a message is passed through.
Any thoughts?
The relevant parts of my index.html page:
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
<body>
<ul id="messages"><ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
My index.js file:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg) {
console.log("message: " + msg);
});
});

I've gotten it to work!
Steps to solution:
- separate the script tag with the event listener into a separate JS file
- include that JS file in the same place the script tag was originally
- load the chatListener when the document is ready
My files now look like this and everything works beautifully:
index.html:
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="main.js"></script>
<body>
<ul id="messages"><ul>
<form action="">
<input class="chat" id="m" autocomplete="off" />
<input class="btn" type="submit" value="Send" />
</form>
</body>
index.js: nothing changed
main.js:
var socket = io();
var chatListener = function() {
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
}
$(document).ready(function() {
chatListener();
})
In the end, I think it was a beginner's JS mistake; I was loading the script at the top of the page (as the tutorial suggested), and the event listener on the form was never registering.

Related

node.js socke.io chat app : not sending message between two browser windows where is my mistake

js code. which is a server file
while i am running this below code it is not sending messages when i click the button.
var express = require('express');
var socket = require('socket.io');
var app = express();
var server = app.listen(8000,function(){
console.log("The server is listening on the port 8000");
});
app.use(express.static('public'));
var io = socket(server);
io.on('connection', function(socket){
socket.on("chat", function(data){
io.sockets.emit("chat", data);
});
});
here is my index.html code which also contains
and css file which i am not included here
<!DOCTYPE html>
<html>
<head>
<title>my first chat app</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js">
</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="mario-chat">
<div id="chat-window">
<div id="output"></div>
<div id="feedback"></div>
</div>
<input id="handle" type="text" placeholder="Handle"/>
<input id="message" type="message" placeholder="Message"/>
<button id="send">Send</button>
</div>
<script src="/chat.js"></script>
</body>
</html>
the above code include a stylesheet.css file for looking good.
here is my chat.js file which is client side functionalities.
var socket = io.connect("http://localhost:8000");
var message = document.getElementById("message");
var handle = document.getElementById("handle");
var btn = document.getElementById("send");
var output = document.getElementById("output");
var feedback = document.getElementById("feedback");
btn.addEventListener("click",function(){
socket.emit("chat", {message:message.value,handle:handle.value});
});
socket.on("chat", function(data){
output.innerHTML += '<p><strong>' + data.handle + ':</strong>' +
data.message + '</p>';
});
please rectify me where i am doing mistakes
thanks in advance.
In your client code socket must be created with ws protocol. So,
io.connect("http://localhost:8000"); should be io.connect("ws://localhost:8000");

socket.to(socket.id).emit() does not work

Trying to execute the simplest of targeted messaging in socket.io with no success. According to the documentation for socket.io with express.js you can target a message to a single user socket with socket.to(socket.id).emit('event name', 'message')
I have already read the socket.io docs from start to finish and other stack overflow Q/A here and here and here. Some of the solutions I find involve creating rooms and messaging those rooms, but the objective of this question is to send a message to the socket id using socket.to(socket.id).emit('event name', 'message') as given in the socket.io documention.
I'm using node v6.11.2, express 4.15.2 and socket.io 2.0.3.
The client and server code are taken almost verbatim from https://socket.io/get-started/chat/ with minor changes while I experiment.
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
io.on('connection', function(socket){
console.log(req.ip+' connected');
socket.on('chat message', function(msg){
console.log(socket.id);//logs the socket id. Something like 'AUCyM1tnpinCfvfeAAAB'
console.log(msg);//logs whatever the message was, so I know the server is receiving the message
socket.to(socket.id).emit('chat message', 'Nothing is happening here.');
});
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
...
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
Change this:
socket.to(socket.id).emit(...)
to this:
socket.emit(...)
Here's an explanation. socket.to(socket.id).emit(...) will broadcast to the room named socket.id. That's OK, there is a room with that name and socket is the only member. But, socket.to() sends to all members of that room EXCEPT socket so there's nobody to send it to.
So, if you want to send just to socket, then just use socket.emit().
Here's a quote from the socket.io doc for socket.to():
Sets a modifier for a subsequent event emission that the event will
only be broadcasted to clients that have joined the given room (the
socket itself being excluded).
Change this :
socket.to(socket.id).emit('chat message', 'Your message');
To this :
io.to(socket.id).emit('chat message', 'Your message');
if you want you can check this link : https://socket.io/docs/emit-cheatsheet/

nodejs terminal:console.log can't print

app.js
app.get('/',function(req,res){
res.sendfile(__dirname + '/index.html');
console.log('hhh');
});
io.sockets.on('connection',function(socket){
socket.on('nickname',function(data){
console.log('The sever received the following nickname: ' +data);
});
});
index.html
<h1>Socket.IO Express Example</h1>
<form id="set-nickname">
<label for="nickname">Nickname:</label>
<input type="text" id="nickname">
<input type="submit" value="submit">
</form>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();
jQuery(function($){
var nickName = $('#nickname');
var setNacknameForm = $('#set-nickname');
setNacknameForm.submit(function(event){
event.preventDefalut();
socket.emit('nickname',nickName.val());
});
});
</script>
hhh can print in terminal browser but I enter words in browser, I click submit, nothing is printed in terminal.
I'm using express version 4.x
What should I do?

Chat Server With NodeJS and Socket.io

I've Written This script for the server
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/' , function(req,res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection' , function(socket){
socket.on('send message' , function(data){
io.sockets.emit('new message' , data);
});
});
And This Is The Chatting Page
<html>
<head>
<title>Chat Program</title>
<style>
#chat{
height:400px;
}
</style>
<script src="http://code.jquery.com/jquery-latest-min.js"></script>
<script src="/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
var $messageform = $('#send-message');
var $messagebox = $('#message');
var $chat = $('#chat');
$messageform.submit(function(e){
e.preventDefault();
socket.emit('send message' , $messagebox.val());
$messagebox.val("");
});
socket.on('new message' , function(data){
$chat.append(data + "<br/>");
});
});
</script>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
</body>
</html>
When I Run The script from the console it runs well but when i write something in the chatting box nothing happen... I Don't Know Why But i think that the folder which i downloaded from "npm install socket.io-client" have a problem.
This Line ==> <script src="/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>I Think The Problem is here as the whole code is proper and right (I think)
hint : I'm Node.js beginner
You dont have express configured to serve the file. You have 2 options. You can:
configure express to serve that file explicitly
add this to your app file:
app.get('/socket.io.js' , function(req,res){
res.sendfile(__dirname + '/node_modules/socket.io/node_modules/socket.io-client/socket.io.js');
});
and switch your html script to:
<script src="/socket.io.js"></script>
configure express to server any file in a directory (see this)

Redis Cookbook Chat Recipe

I am a new starter to Node.Js and Redis. I got the Redis cookbook and was trying out the Chat client & Server recipe.
I was wondering if anybody got the code to work or if there is some bug in the code.
I dont see where the sent messages from the client get invoked on the server.
Any help would be great.
Regards,
Tom
Client Code:
<?php
?>
<html>
<head>
<title></title>
<script src="http://192.168.0.118:8000/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>
var socket = io.connect('192.168.0.118',{port:8000});
socket.on('message', function(data){
alert(data);
//var li = new Element('li').insert(data);
//$('messages').insert({top: li});
});
</script>
</head>
<body>
<ul id="messages">
<!-- chat messages go here -->
</ul>
<form id="chatform" action="">
<input id="chattext" type="text" value="" />
<input type="submit" value="Send" />
</form>
<script>
$('#chatform').submit(function() {
socket.emit('message', 'test'); //$('chattext').val());
$('chattext').val(""); // cleanup the field
return false;
});
</script>
</body>
</html>
Server Code:
var http = require('http');
io = require('socket.io');
redis = require('redis');
rc = redis.createClient();
//rc1 = redis.createClient();
rc.on("connect",function(){
rc.subscribe("chat");
console.log("In Chat Stream");
});
rc.on("message",function (channel,message){
console.log("Sending hope: " + message);
//rc1.publish("chat","hope");
socketio.sockets.emit('message',message);
});
server = http.createServer(function(req,res){
res.writeHead(200,{'content-type':'text/html'});
res.end('<h1>hello world</h1>');
});
server.listen(8000);
var socketio = io.listen(server);
It looks like you're not listening for any connect / message events from socket.io.. try something like
socketio.sockets.on('connection', function(socket) {
console.log("Got connection");
socket.on('message', function(msg) {
rc1.publish("chat", msg);
});
});
You'll need to uncomment your rc1 up there, you will need that second redis connection

Resources