Client is not receiving message from server in socket.io

3.5k views Asked by At

My server wants to send to the clients a message on connection. Then the client sends a message to the server .

My code is working fine when the client sends message to the server but the initial message that the server should send on connection is not received by the client.

This is my little code :)

server

var app = require('http').createServer(handler),
  io = require('socket.io').listen(app, { log: false }),
  fs = require('fs');

app.listen(8001);

function handler(req, res) {
  fs.readFile(__dirname + '/client1.html', function(err, data) {
    if (err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error loading client1.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
    console.log("running time");
  socket.emit("serverMessage","server says hi");

  socket.on('clientMessage', function () {
       console.log("client message recieved");
  });      
});

client

 <html>
  <head>
    <script src="/socket.io/socket.io.js"></script>
       <script>
         socket = io.connect("http://localhost:8001");
          socket.on('connection', function(socket) {
               socket.on("serverMessage", function(d) {
               console.log("server send a message ");
              });          
         });
        function send() {
            socket.emit('clientMessage', "Test Message From Client");
        }
    </script>
</head>

<body>
    <button onclick="send()" >send</button>

</body>

Please any help?

1

There are 1 answers

4
M Omayr On BEST ANSWER

There is a simple error in your client code. There is no event named connection for client. Instead the name is connect. Do this in client:

<script>
     socket = io.connect("http://localhost:8001");
</script>
<script>
socket.on('connect', function(socket) {
    socket.on("serverMessage", function(d) {
    // you can alert something here like alert(d)
    console.log("server send a message ");
    });          
});
</script>