0

I'm trying an example of WebSocket to develop a simple chat.

server.js:

var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')

app.listen(8080);

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

    res.writeHead(200);
    res.end(data);
  });
}

and test.html:

<script src="/socket.io/socket.io.js"></script>
<script>
 var socket = io.connect('http://localhost');

 socket.on('connect', function() {
  alert('<li>Connected to the server.</li>');
 });

 socket.on('message', function(message) {
    alert(message);
 });

 socket.on('disconnect', function() {
   alert('<li>Disconnected from the server.</li>');
 });

 function sendF(){
    var message = "Test";
    socket.send(message);
    alert('Test Send');     
}

In test.html I have also a simple button that onClick call sendF.

If I try it I see on my browser an alert when I CONNECT, SEND, and DISCONNCT, and if I check in console, I see the message.

But I cannot receive the same message in response from server, to show it in my browser! I think socket.on('message'... is not working for me!

2
  • I have no experience with socket.io, but a WebSockets server is not supposed to return HTML headers and contents like you are doing. Are you sure you're creating a WebSockets server? Commented Oct 1, 2011 at 15:20
  • socket.io doesn't necessarily create webSockets. Socket.io finds the best protocol available, like long polling, and uses it. Commented Oct 1, 2011 at 23:33

1 Answer 1

2

Your server.js is missing event listeners. It's also missing where you are doing the send of the message to be displayed in the browser.

io.sockets.on('connection', function (socket) {
  console.log('user connected');
  socket.send('hello world');
  socket.on('disconnect', function () {
    console.log('user disconnected.');
  });
  socket.on('message', function (data) {
    console.log(data);
  });
});
Sign up to request clarification or add additional context in comments.

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.