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>
Related
Node.js Server
var app = require ('express')();
var http = require ('http').Server(app);
var io = require('socket.io')(http);
var users=0;
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection',function(socket){
users++;
console.log('a user connected');
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('disconnect', function(){
users--;
console.log('user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
http://localhost:3000 it can hold index.html and works well
but http://104.155.198.127:3000 it responds (This site can't be reached)
104.155.198.127 is real ip
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);
});
});
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>
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;
});
});
I want to send message to users if some new person is joining or user is quiting the chat.
i don't really know where to start to get this function work.
On disconnect message 'This users is gone' to all On Connect "user is connected to the chatbox"
app.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
nicknames = [];
server.listen(8000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
socket.on('new user', function(data, callback){
if (nicknames.indexOf(data) != -1){
callback(false);
} else{
callback(true);
socket.nickname = data;
nicknames.push(socket.nickname);
updateNicknames();
}
});
function updateNicknames(){
io.sockets.emit('usernames', nicknames);
}
socket.on('send message', function(data){
io.sockets.emit('new message', {msg: data, nick: socket.nickname});
});
socket.on('disconnect', function(data){
if(!socket.nickname) return;
nicknames.splice(nicknames.indexOf(socket.nickname), 1);
updateNicknames();
});
})
;
You can use the broadcast function. This will broadcast to every other socket except the one that send the broadcast.
socket.on('disconnect', function () {
socket.broadcast.emit('leave',{name:name});
});
socket.on('leave', function (msg) {
//Add msg that msg.name is leaving
});