jd182
jd182

Reputation: 3260

socket.io client unable to emit message to server

I can't figure out why my socket.io server isn't receiving messages from the client. Here is my server JS file:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

    console.log('a user connected');

    socket.on('bid', function(msg){
        console.log('received:' + msg);
    });

    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

And here is the client-side code:

$(function () {

    var socket = io(':3000/socket.io/socket.io.js');

    $('#bid-form').on('submit',function(){
        socket.emit('bid', 'test');
        console.log('emit');
        return false;
    });
});

When I open and close the browser page I see the "user connected" and "user disconnected" messages on the server console so I know it's making the connection.

When I submit the form I see the "emit" message in the browser console so I know the form submit event is firing but I'm not receiving the test message on the server. Nothing seems to happen on the client or sever end, it seems like the "socket.emit" function isn't doing anything.

What am I doing wrong?

Upvotes: 1

Views: 631

Answers (1)

Jay Lim
Jay Lim

Reputation: 412

My assumption is that you are running your express server on localhost.

It looks like you're accessing your HTML file directly through file:// unless your client-sided code is hosted by a different web server. But regardless of that, here's how you can connect:

<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io("http://localhost:3000");
    $('#bid-form').on('submit',function(){
      socket.emit('bid', 'test');
      console.log('emit');
      return false;
    });
  });
</script>

You will need to load the socket.io.js file through the script tag. Then connect to your socket.io server by providing the host of the socket.io server to the io() function.

Upvotes: 3

Related Questions