【问题标题】:Why my simple chat in nodejs using websockets won't send messages为什么我在 nodejs 中使用 websockets 的简单聊天不会发送消息
【发布时间】:2017-03-29 16:54:02
【问题描述】:

聊天是使用 socket.io 库中的 websockets 在 nodejs 中编程的,我有一个客户端也使用 socket.io 中的 websockets,但我无法使两者一起工作。出于某种原因,客户端没有将消息发送到服务器(我有一个 console.log 函数,它应该在收到消息时写入控制台,但它什么都不写)。

服务器的代码是:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
       console.log('message: ' + msg);
    io.emit('chat message', msg);
  });
});

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

对于客户来说:

<!DOCTYPE html>
<html>
<head>
    <style>
        * { margin:0; padding:0; font-size:11px; font-family:arial; color:#444; }
        body { padding:20px; }
        #message-list { list-style-type:none; width:300px; height:300px; overflow:auto; border:1px solid #999; padding:20px; }
        #message-list li { border-bottom:1px solid #ccc; padding-bottom:2px; margin-bottom:5px; }
        code { font-family:courier; background:#eee; padding:2px 4px; }
    </style>
    <script src="http://cdn.socket.io/stable/socket.io.js"></script>
    <script>



        // Sends a message to the server via sockets
        function sendMessageToServer(message) {
            socket.send(message);
            log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
        }

        // Outputs to console and list
        function log(message) {
            var li = document.createElement('li');
            li.innerHTML = message;
            document.getElementById('message-list').appendChild(li);
        }


        // Create a socket instance
        socket = new WebSocket('ws://localhost:8080');

        // Open the socket
        socket.onopen = function(event) {
            console.log('Socket opened on client side',event);

            // Listen for messages
            socket.onmessage = function(event) {
                console.log('Client received a message',event);
            };

            // Listen for socket closes
            socket.onclose = function(event) {
                console.log('Client notified socket has closed',event);
            };

        };


    </script>
</head>
<body>

    <p>Messages will appear below (and in the console).</p><br />
    <ul id="message-list"></ul>
    <ul style="margin:20px 0 0 20px;">
        <li>Type <code>socket.disconnect()</code> to disconnect</li>
        <li>Type <code>socket.connect()</code> to reconnect</li>
        <li>Type <code>sendMessageToServer('Your Message')</code> to send a message to the server</li>
    </ul>

</body>
</html>

你知道这里有什么问题吗? 提前致谢!

【问题讨论】:

  • 请尝试从socket.on('chat message' 更改为socket.on('message'。根据docssocket.send 发送message 事件。,所以你需要在服务器中侦听正确的。
  • 另外,那个cdn坏了……也许你只是在学习一个过时的教程,请参考:https://socket.io/get-started/chat/
  • 我将“聊天消息”更改为“消息”,但仍然是同样的问题
  • socket.io/get-started/chat :这是我遵循的确切教程,它使用“聊天消息”而不是“消息”
  • 首先,教程使用jquery(但我是合理的,如果你改变它就可以了)。其次,他们使用socket.emit,而不是socket.send.. 再次,如果你按F12,在控制台中你会看到你试图从中获取socket.io 的cdn 已经死了。哦,好吧

标签: javascript node.js sockets websocket


【解决方案1】:

根据我的知识,您有几个问题。如果它们都已修复,它应该可以工作。

  1. 连接socket.io.js文件应该是你自己的。在你的情况下,我猜它是 &lt;script src="http://localhost:3000/socket/socket.io.js"&gt;&lt;/script&gt; 我不能 100% 确定,因为你的端口可能会有所不同。
  2. 您没有在客户端正确定义套接字。将其定义为:var socket = io();。你这样做的方式是socket = new WebSocket('ws://localhost:8080'); 未定义 WebSocket 的地方。并且,代码将创建一个新的 websocket 服务器,您已经在服务器代码中这样做了。您需要在客户端做的只是连接到服务器。
  3. 您必须使用相同的通道让客户端和服务器进行通信。因此,在您的客户端代码中,您应该发送这样的消息socket.emit('chat message', 'content you want to send'
  4. 我不知道你为什么再次在服务器端发出消息顺便说一句。我假设您正在从客户端向服务器发送消息。所以你不应该在你的服务器代码中发出命令。

如果这四件事都解决了,它就会起作用。

如果我表达不清楚,我为你写了一个超级简单的例子:

服务器端:

let io = socketio(server.listener);
io.on("connection", function(socket) {
    console.log("A user connected");

    // auto messages when a user is connected
    setTimeout(function() {
        socket.send("message at 4 seconds");
    }, 4000);
    setTimeout(function() {
        socket.send("message at 8 seconds");
    }, 8000);

    // callback when a user disconnected
    socket.on("disconnect", function(){
        console.log("A user disconnected");
    });

    // receive message from client
    socket.on("client-server", function(msg) {
        console.log(msg);
    });
});

// you put this code anywhere when you need to send message from server to client
io.emit("server-client", "server to client message");

客户端:

<!DOCTYPE html>
<html>
  <head><title>Hello world</title></head>
  <script src="http://localhost:3000/socket.io/socket.io.js"></script>
  <script>
    var socket = io();
    socket.on('server-client', function(data) {document.write(data)});
    socket.emit('client-server', 'test message');
  </script>
  <body>Hello world</body>
</html>

我的服务器代码是用 typescript 编写的,所以不要介意 let 关键字、双引号等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多