Socket.io Chat not working on server - node.js

My chat application is working properly on local server, but when I am pushing it to the openshift server, the chat functionality is not working.
I am following this example : http://socket.io/get-started/chat/
The following is my HTML code
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><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());
$('#m').val('');
return false;
});
socket.on('chat message', function (msg) {
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
Below is my server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
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(port, function () {
console.log('listening');
});
The same code is working fine on my local server. For now I am simply broadcasting the message including the sender too.
Where am I wrong?

$( document ).ready(function() {});
this code saved me. i forgot to enclose my scripting in jquery document ready. so the final code looks like this.
$( document ).ready(function() {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});

Your chat client needs to connect to the websocket chat server on port 8000 for ws (or 8443 for wss). Make sure you are specifying that port number when you have it connect.

I know it´s a bit late, but the document isn´t ready and that caused the error.
Try this code:
$( document ).ready(function() {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});

Related

Socket.io getting disconnected unexpectedly

<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button onclick="message()">Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var message = function(){
var msg = document.getElementById("m").value;
if(msg !== ""){
alert(msg);
socket.emit('chat message',msg);
}
document.getElementById("m").value="";
}
socket.on('display',function(value){
console.log(value);
document.getElementById("messages").innerHTML += "<li>"+value+"</li>";
})
</script>
This is my index.html page to design a group chat using socket.io
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(request, response) {
response.sendFile(__dirname + '/index.html');
});
io.on('connection',function(socket){
console.log('a user connected');
socket.on('chat message',function(msg){
console.log('message: '+msg);
io.emit('display',msg);
});
socket.on('disconnect',function(){
console.log('user disconnected')
})
});
http.listen(3000, function() {
console.log("listening on 3000");
});
This is my index.js file. The user is getting disconnected each time a message is sent. Any suggestions why this happened
Thanks in advance
Add message(event) to your form:
<form action="">
<input id="m" autocomplete="off" /><button onclick="message(event)">Send</button>
</form>
and change your message function to:
var message = function(event){
event.preventDefault();
var msg = document.getElementById("m").value;
if(msg !== ""){
alert(msg);
socket.emit('chat message',msg);
}
document.getElementById("m").value="";
}
The default html method when you submit a form is GET. When express receives GET it resends index.html to the browser and the page refreshes. We can change it with event.preventDefault(). It should work now.
You shouldn't do:
io.emit
You should do:
socket.emit

socket io not parse string and any characters

I want send simple message to node.js console from html. But number is working , string and any characters not working,
Display message is
message: NaN
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile('sample.html', {
root:'/home/deneebo/Documents/apidevelopment/nodejs'});
});
io.on('connection', function(socket) {
socket.on('chat message', function(msg) {
console.log('message: ', + msg);});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
below html code
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
</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="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
alert($('#m').val());
$('#m').val('');
return false;
});
</script>
</body>
</html>
I tried your code my local work well
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('stack.html', {root: __dirname });
});
io.on('connection', function(socket) {
socket.on('chat message', function(msg) {
console.log('message: ', msg);}); //Remove + from here
});
http.listen(3000, function(){
console.log('listening on *:3000');
});

Socket.io connect event not firing

This is my first time working with node.js/socket.io and I'm having a little trouble with the 'connect' event firing for all sockets. I followed the chat application example and then tried to add a feature where instead of displaying in the console when a user connects or disconnects, I would display it on-screen.
The disconnect event is firing for all tabs (if I have multiple tabs open to the chat application), but the connect event only seems to fire for the current tab.
Server (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('connect', function(){
io.emit('connect', "A user connected");
});
socket.on('disconnect', function(){
io.emit('disconnect', "A user disconnected");
});
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Client (index.html)
<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));
});
socket.on('disconnect', function(msg){
$('#users').text(msg);
});
socket.on('connect', function(msg){
$('#users').text(msg);
});
</script>
Ensure that your socket.io client and server are same major version of socket.io. E.g use socket.io#2.3.0 on both server and client or socket.io-client#3.. on both server and client.
There are two problems I can see with your code.
One is you don't need a socket "on connect" function. You can just put your code in the io "on connection", and it will fire when the user connects.
io.on("connection", function (socket) {
// Do connect stuff here
})
The other is that in your socket disconnect function, you emit disconnect which is could cause problems because it shares the name with other functions. Do something like this instead:
//Server:
io.on('connection', function(socket){
io.emit('set users', "A user connected");
socket.on('disconnect', function(){
io.emit('set users', "A user disconnected");
});
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
//Client:
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));
});
//You only need one function to set "#users"
socket.on('set users', function(msg){
$('#users').text(msg); //this will set the text in #users
});
You can try this, it may work:
server:
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){
io.emit('new user', "A user connected");
socket.on('disconnect', function(){
io.emit('disconnect', "A user disconnected");
});
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
client:
<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('connect', function() {
$('#users').text('I am connected!');
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
socket.on('disconnect', function(msg){
$('#users').text(msg);
});
socket.on('new user', function(msg){
$('#users').text(msg);
});
</script>

How to write tests: Socket.io app unit testing

I am trying to make simple chat app using socket.io. Manually it's working fine (via browser localhost:3000/) but I want to write unit tests to verify logic of the server. I don't know which tools/libraries to use for testing.
Here is my node server code:
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketCount = 0;
http.listen(3000, function(){
console.log('listening on *:3000');
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
socketCount++;
console.log('new user connected');
// Let all sockets know how many are connected
io.emit('users connected', socketCount);
socket.on('disconnect', function(){
// Decrease the socket count on a disconnect, emit
socketCount--;
io.emit('users connected', socketCount);
});
socket.on('chat message', function(msg){
// New message added, broadcast it to all sockets
io.emit('chat message', msg);
});
});
And here is my html page:
file: index.html
<html>
...
<body>
<ul id="messages"></ul>
<div class='footer'>
<div id="usersConnected"></div>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</div>
</body>
...
<script>
$(document).ready(function(){
$('#messages').val('');
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
// New message emitted, add it to our list of current messages
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
// New socket connected, display new count on page
socket.on('users connected', function(count){
$('#usersConnected').html('Users connected: ' + count);
});
});
</script>
</html>
Thanks.
I had this problem: How to do unit test with a "socket.io-client" if you don't know how long the server take to respond?.
I've solved so using mocha and chai:
var os = require('os');
var should = require("chai").should();
var socketio_client = require('socket.io-client');
var end_point = 'http://' + os.hostname() + ':8081';
var opts = {forceNew: true};
describe("async test with socket.io", function () {
this.timeout(10000);
it('Response should be an object', function (done) {
setTimeout(function () {
var socket_client = socketio_client(end_point, opts);
socket_client.emit('event', 'ABCDEF');
socket_client.on('event response', function (data) {
data.should.be.an('object');
socket_client.disconnect();
done();
});
socket_client.on('event response error', function (data) {
console.error(data);
socket_client.disconnect();
done();
});
}, 4000);
});
});

socket.io polling 404 error

I try to learn socket.io on my web server. I have installed node.js and socket.io on my server. I have prepared web site my socket javascript code is work properly -listening port 3000 on console- but when i try to run example chat application, i got "socket.io/?EIO=3&transport=polling&t=1423949334574-31 404 (Not Found)" error. Where is mistake?
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(3000, function(){
console.log('listening on *:3000');
});
There is my index.html script:
<script>
var socket = io("http://localhost:3000");
$('form').submit(function(){
socket.emit('chat message', $('#messagebox').val());
var mesaj = $('#messagebox').val();
$('.messageBoard').prepend('<p style="display: none">'+mesaj+'</p>');
$('#messagebox').val('');
$('.messageBoard').find('p:first-child').show('slideDown');
e.preventDefault();
return false;
});
socket.on('chat message', function(msg){
$('.messageBoard').prepend('<p style="display: none">'+mesaj+'</p>');
});
</script>

Resources