【问题标题】:Client is not receiving message from server in socket.io客户端未在 socket.io 中接收来自服务器的消息
【发布时间】:2014-03-17 09:18:32
【问题描述】:

我的服务器想在连接时向客户端发送一条消息。然后客户端向服务器发送消息。

当客户端向服务器发送消息时,我的代码工作正常但客户端未收到服务器应在连接时发送的初始消息。

这是我的小代码:)

服务器

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");
  });      
});

客户

 <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>

请帮忙?

【问题讨论】:

    标签: javascript node.js socket.io client-server


    【解决方案1】:

    您的客户端代码中有一个简单的错误。客户端没有名为 connection 的事件。相反,名称是connect。在客户端执行此操作:

    <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>
    

    【讨论】:

    • 感谢@M Omary 的回答 :) 你能指导我到 socket.io 上的好教程
    • 好吧,我从 github github.com/LearnBoost/Socket.IO/wiki 和他们的官方网站 socket.io 了解了 socket.io,你可以在谷歌上搜索 socket.io 教程,你会在那里找到很棒的东西
    • 我忘了一件事,你也可以在 'connect' 事件的范围之外这样做:socket.on('connect',function(){alert('Test');}) ; socket.on('serverMessage',function(data){alert('data');});
    • 谢谢!!我迷失在谷歌中,就是这么简单。
    猜你喜欢
    • 1970-01-01
    • 2012-04-07
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2017-04-22
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多