0

While trying to setup a simple NodeJS server and Socket.io client to test something with WebSockets, I've stumbled into something stupid. I'm pretty sure it's something stupid I've done because I've worked with NodeJS/Socket.io before and never had this problem.

With the code below, I'm able to receive the 'tick' event from the server on the client, but the server seems unable to receive the 'ping' event from the client. 'tick' was used to make sure server->client worked, and 'ping' to test client->server.

Using latest Socket.io (1.4.6) and express (4.14.0)

server.js:

var express = require('express');
var app = require('express')();
var server = require('http').createServer(app);
var sio = require('socket.io')(server);
var path = require('path');

app.use(express.static(path.join(__dirname, 'public_html')));

// Socket.io
sio.on('connection', (socket) => {
    // Store socket ID
    var socketID = socket.conn.id;

    // Log connection
    console.log('Connection:', socketID);

    // Ping event
    socket.on('ping', (message) => {
        console.log('Ping:', socketID, '-', (message || '(no message>'));
    });

    // Tick event
    var tick = function(){
        var now = new Date().getTime().toString();
        socket.emit('tick', now);
    }
    setInterval(tick, 5000);

    // Disconnect event
    socket.on('disconnect', () => {
        console.log('Disconnected:', socketID);
    });
});

server.listen(4100, () => {
    console.log('Listening on :4100');
});

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Websockets Benchmark</title>
</head>
<body>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        // Socket.io
        var sio = io();

        // Connection event
        sio.on('connect', () => {
            console.log('Connected');

            sio.emit('ping', 'on connect');
        });

        // Tick event
        sio.on('tick', (time) => {
            console.log('Tick', time);
        });

        // Error event
        sio.on('error', (e) => {
            console.error(e);
        });
    </script>
</body>

2 Answers 2

1

hope i understood your question... i did some work with chat by using socket.io so maybe it will help you. here it is:

 <div class="searchBox" style="height: 600px ; width: 500px">
      <div style=";width:400px;border-right:1px solid black;;overflow:scroll-y;">
         <b style="color: black ;text-decoration: underline">USERS:</b>
         <div id="users" style="color: black"></div>
      </div>
      <div style=";width:300px;height:250px;overflow:scroll-y;padding:10px;">
         <b style="color: black ; text-decoration: underline">CONVERSATION:</b>
         <div id="conversation" style="color: black"></div>
         <input id="data" style="width:200px;" />
         <button id="datasend" style="color: #0f0f0f;">send</button>
      </div>

and the js:

var socket = io.connect('http://localhost:8080');
    // on connection to server, ask for user's name with an anonymous callback
    socket.on('connect', function(){
        // call the server-side function 'adduser' and send one parameter (value of prompt)
        socket.emit('adduser', prompt("What's your name?"));
    });
    // listener, whenever the server emits 'updatechat', this updates the chat body
    socket.on('updatechat', function (username, data) {
        $('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
    });
    // listener, whenever the server emits 'updateusers', this updates the username list
    socket.on('updateusers', function(data) {
        $('#users').empty();
        $.each(data, function(key, value) {
            $('#users').append('<div>' + key + '</div>');
        });
    });
    // on load of page
    $(function(){
        // when the client clicks SEND
        $('#datasend').click( function() {
            var message = $('#data').val();
            $('#data').val('');
            // tell server to execute 'sendchat' and send along one parameter
            socket.emit('sendchat', message);
        });
        // when the client hits ENTER on their keyboard
        $('#data').keypress(function(e) {
            if(e.which == 13) {
                $(this).blur();
                $('#datasend').focus().click();
            }
        });
    });

server:

var app = require('./app');
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);

server.listen(8080, function() {
    console.log("Gym Project is listening to: http://127.0.0.1:8080");
});

// routing
app.get('/', function (req, res) {
    res.sendfile(__dirname + '/index.html');
});


// usernames which are currently connected to the chat
var usernames = {};

io.sockets.on('connection', function (socket) {

    // when the client emits 'sendchat', this listens and executes
    socket.on('sendchat', function (data) {
        // we tell the client to execute 'updatechat' with 2 parameters
        io.sockets.emit('updatechat', socket.username, data);
    });

    // when the client emits 'adduser', this listens and executes
    socket.on('adduser', function(username){
        // we store the username in the socket session for this client
        socket.username = username;
        // add the client's username to the global list
        usernames[username] = username;
        // echo to client they've connected
        socket.emit('updatechat', 'SERVER', 'you have connected');
        // echo globally (all clients) that a person has connected
        socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
        // update the list of users in chat, client-side
        io.sockets.emit('updateusers', usernames);
    });

    // when the user disconnects.. perform this
    socket.on('disconnect', function(){
        // remove the username from global usernames list
        delete usernames[socket.username];
        // update list of users in chat, client-side
        io.sockets.emit('updateusers', usernames);
        // echo globally that this client has left
        socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
    });
});

this is a very simple chat with some clients... may it helps :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - your code didn't lead me straight to the answer but I think my events' names collided with those of Socket.io's
0

Can't tell if the ping event is taken by Socket.io, or the following line caused an issue:

console.log('Ping:', socketID, '-', (message || '(no message)'));

Either way, by changing the event name to ev:ping (which is easier to understand anyway), and simplifying that line it's fixed! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.