Socket.io服务器似乎没有连接?

时间:2011-06-02 23:32:45

标签: node.js chat websocket socket.io

我正在研究NodeTuts上的教程。我正在尝试使用socket.io让聊天服务器工作。

我可以正常启动节点实例,当我这样做时,我得到“socket.io ready-acceping connections”消息。当我将我的浏览器指向localhost:8888时,我也从template.html获得html表单,以便所有看起来都很好。我似乎永远不会建立套接字连接,但我从未看到“已接收连接”日志或“欢迎使用聊天服务器”消息。

任何想法是什么问题?

var fs, http, io, server, socket, sys;
  http = require('http');
  fs = require('fs');
  sys = require('sys');
  io = require('socket.io');
  server = http.createServer(function(req, res) {
    var rs;
    console.log('server started');
    res.writeHead(200, {
      'Content-Type': 'text/html'
    });
    rs = fs.createReadStream(__dirname + '/template.html');
    return sys.pump(rs, res);
  });
  socket = io.listen(server);
  socket.on('connection', function(client) {
    var username;
    console.log('Connection received');
    client.send('Welcome to the chat server');
    client.send('Please enter a username');
    return client.on('message', function(message) {
      if (!username) {
        username = message;
        return client.send("Hi " + username + "!");
      } else {
        return socket.broadcast("" + username + ": " + message);
      }
    });
  });
  server.listen(8888);

这是template.html的JS部分

<script src="/socket.io/socket.io.js"></script>
<script>
    $(function() {
      socket = new io.Socket('localhost', {port: 8888});
      socket.on('message', function(message) {
        var data = message.data
        data = data.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        console.log( data );
        $('#log ul').append('<li>' + data + '</li>');
        window.scrollBy(0, 1000000000000000);
        entry_el.focus();
      });


      var entry_el = $('#entry');
      entry_el.keypress(function(event) {
        if (event.keyCode != 13) return;
        var msg = entry_el.attr('value');
        // if the message is not empty
        if (msg) {
            socket.send(msg);
            entry_el.attr('value', '');
        }
      });
    });
  </script>

1 个答案:

答案 0 :(得分:1)

我认为您需要在socket.connect();

之后立即在客户端代码中致电socket = new io.Socket('localhost', {port: 8888});