Socket.io socket.emit not passing data to server - javascript

I was trying my hands on Socket.io.
I have the following code.
This is my index.html.
<!doctype html>
<html>
<body>
<ul id="messages"></ul>
<form action="" onsubmit="return sayHello()">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3001/');
function sayHello(){
var msg = document.getElementById('m');
console.log(msg); <- This is getting printed.
socket.emit('message', msg.value);
msg.value='';
return (false);
}
// $('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>
This is my server.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("GO!") <- This is getting printed
socket.on('chat message', function(msg){
console.log(msg); <- This is not getting printed.
io.emit('chat message', msg);
});
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
I have cloned the sample project from the Socket.io website. I was trying to modify some code by replacing the Jquery with VanillaJS.

You are listening for chat message but emitting message from client. Event name provided with .emit must match with the event name being listened on the server in .on handler.
//SERVER SIDE CODE
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("GO!") < -This is getting printed
socket.on('chat message', function(msg) {
console.log(msg); < -This is not getting printed.
io.emit('chat message', msg);
});
});
http.listen(3001, function() {
console.log('listening on *:3001');
});
<!doctype html>
<html>
<body>
<ul id="messages"></ul>
<form action="" onsubmit="return sayHello()">
<input id="m" autocomplete="off" />
<button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3001/');
function sayHello() {
var msg = document.getElementById('m');
console.log(msg); < -This is getting printed.
socket.emit('chat message', msg.value);
//-----------^^^^^^^^^^^^ Event name must match with the `.on` listener on the server!
msg.value = '';
return (false);
}
</script>
</body>
</html>

Related

socket io not giving the desired output

I have created a index.js which loads index.html using sockets.
the server is running successfully and also the index.html page loads. but cant append the written text in the div.
index.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000, function() {
console.log("SERVER CREATED WITH PORT 3000");
});
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
socket.on('send', function(data) {
io.sockets.emit('new', data);
});
});
index.html
<html>
<head>
<title>chat</title>
<style>
#chat {
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input id="message" />
<input type="submit" />
</form>
<h1>Working</h1>
<script src="jquery-3.2.1.min.js"></script>
<script src="/socket.io/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', $messagebox.val());
$messagebox.val('');
});
socket.on('new', function(data) {
$chat.append(data + "<br />");
});
});
</script>
</body>
</html>
These are the files which I have created and want to send the text to all tabs.
The browser just gets refreshed without loading the text when submit is hit.
Please let me know what I am doing wrong.

socket.io chat example doesn't work after form submit

I followed the chat tutorial from socket.io (http://socket.io/get-started/chat/), but once I come to the part I have to get information from the form I get stuck.
The warnings I get from my index.html file are:
io is not defined please fix or add global io
$ is not defined please fix or add global $
I tried adding the website link to the <script src="/socket.io/socket.io.js"> however this had no effect. I am using c9.io as my development tool. using node.js and socket.io.
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){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(process.env.PORT, process.env.IP, function() {
console.log("listening on *:" + process.env.PORT);
});
index.html
<!-- I did not include the html and head tags in this example for readability purposes -->
<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="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;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
Add event window ready
var socket = io();
$(document).ready(function(){
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});

Node.js chat app with username variables not working

I'm making a chat app in node.js based on a tutorial from socket.io. The purpose is for a user to enter in a username and a message. The chat will display "username: message". The username text field will then disappear after the first entry. I have it all working except for the chat displaying the message with the username. The chat displays four messages instead of one, they say that both variables are undefined.
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('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
io.on('connection', function(socket){
socket.on('chat message', function(msg, usn){
io.emit('chat message', msg);
io.emit('chat message', usn);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
HTML (Without the style tags)
<!doctype html>
<html>
<head>
<title>Lucas Chat</title>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="u" autocomplete="off" placeholder="Nickname"/><input id="m" autocomplete="off" placeholder="Message"/><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.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());
socket.emit('chat message', $('#u').val());
$('#u').css("display", "none")
$('#m').css("width", "90%")
$('#m').val('');
return false;
});
socket.on('chat message', function(msg, usn){
$('#messages').append($('<li>').text(usn + ": " + msg));
});
</script>
</body>
</html>
clientside
var socket = io();
$('form').submit(function(){
socket.emit('send message', {msg:$('#m').val(),user:$('#u').val()});
$('#u').css("display", "none")
$('#m').css("width", "90%")
$('#m').val('');
return false;
});
socket.on('receive message', function(msg){
$('#messages').append($('<li>').text(msg));
});
and serverside
io.on('connection', function(socket){
socket.on('send message', function(data){
io.emit('receive message',data.msg + ':' + data.user);
});
});

Socket.io: Node.js can't receive event message via method socket.on('message', ...) on AWS

I'm having this problem even with the Socket.io official chat sample.
I had this set up on AWS. I could only received the 'successfully connected' message on the terminal but not the 'message: ....'. Even with Google Dev Tool I couldn't saw any related error. Anyone could help?
Here's the client side javascript code:
<script src="https://cdn.socket.io/socket.io-1.3.4.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>
Then the server side node.js code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
http.listen(8989, function(){
console.log('listening on *:8989');
});
io.on('connection', function(socket){
console.log('successfully connected');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
There is no form submit on button click, also form submit will create a lot of page refreshes and everything, and also you dont need a form for this exercise
Create a function sendMessage()
<script>
var socket = io();
function sendMessage(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
}
</script>
In your HTML remove form and add onclick to button
<body>
<ul id="messages"></ul>
<input id="m" autocomplete="off" /><button onclick="sendMessage()">Send</button>
</body>
It turned out the problem was on the client side javascript code.
I referred to this sample code and found that on socket.io official website it says in some cases (Express 3/4 or the framework) you need to use io.connect() instead of io(). However it works for me in my previous case.
Here's the changed code:
var socket = io.connect();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});

Using disconnect function on socket.io and node.js

I am trying to have it so when a user disconnects from my chat room, it pops up with " has left chat room".
Here is my server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('chat/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('disconnect', function(nickname){
io.emit('disconnect', nickname);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
And here is my client code:
var socket = io();
var nickname;
var leaving;
$('messageForm').submit(function(){
socket.emit('chat message', (nickname + ": " + $('#m').val()));
$('#m').val('');
return false;
});
$('#nicknameForm').submit(function(){
nickname = $('#nickname').val();
if(nickname ==''){
alert("Please enter a value");
}else{
$( "#dialog" ).dialog( "close" );
leaving = nickname + " has left";
}
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
socket.on('disconnect', function(nickname){
socket.emit('disconnect message', nickname);
});
At the moment, nothing appears at all, and I'm not too sure why.
You need to emit a unique event to the clients when another client disconnects.
Change the following:
socket.on('disconnect', function() {
io.emit('disconnect', nickname);
});
To something like this:
socket.on('disconnect', function() {
socket.broadcast.emit('user disconnect', nickname);
});
And add this to your client code:
socket.on('user disconnect', function(nickname){
$('#messages').append($('<li>').text(nickname+' has left the channel.'));
});

Categories