简体   繁体   English

为什么我在使用WebSocket的Node.js中进行简单聊天不会发送消息

[英]Why my simple chat in nodejs using websockets won't send messages

The chat is programmed in nodejs using websockets from socket.io library and i have a client that also uses websockets from socket.io but I don't manage to make the two work together. 聊天是使用来自socket.io库的websockets在nodejs中编程的,我有一个客户端也使用来自socket.io的websockets,但是我无法使两者一起工作。 For some reason the client doesn't send the message to the server (I have a console.log function that should write to console when it receives a message but it doesn't write anything). 出于某种原因,客户端不会将消息发送到服务器(我有一个console.log函数,当它收到消息时它应该写到控制台,但是不写任何东西)。

The code for the server is: 服务器的代码是:

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

And for the client is : 对于客户而言:

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

Do you have any idea what is wrong here? 你知道这里有什么问题吗? Thanks in advance! 提前致谢!

You have a couple issues based on my knowledge. 根据我的知识,您有几个问题。 If they are all fixed, it should work. 如果它们都是固定的,它应该可以工作。

  1. The connection socket.io.js file should be your own one. 连接socket.io.js文件应该是您自己的文件。 In your case, I am guessing it is <script src="http://localhost:3000/socket/socket.io.js"></script> I am not 100 percent sure because your port could vary. 在您的情况下,我猜这是<script src="http://localhost:3000/socket/socket.io.js"></script>我不确定100%,因为您的端口可能会有所不同。
  2. You didn't define socket properly on your client side. 您没有在客户端正确定义套接字。 Define it as this: var socket = io(); 定义为: var socket = io(); . The way you did it is socket = new WebSocket('ws://localhost:8080'); 您的操作方式是socket = new WebSocket('ws://localhost:8080'); Where WebSocket is not defined. 未定义WebSocket的位置。 And, the code will create a new websocket server, which you already did in your server code. 并且,该代码将创建一个新的websocket服务器,您已经在服务器代码中完成了此操作。 What you need to do at client side is only connect to the server. 您需要在客户端执行的操作仅是连接到服务器。
  3. You must use the same channel to let the client and server to communicate. 您必须使用相同的通道,以使客户端和服务器进行通信。 So in your client code, you should send message like this socket.emit('chat message', 'content you want to send' . 因此,在客户端代码中,您应该发送类似于socket.emit('chat message', 'content you want to send'
  4. I don't know why you emit the message at server side again BTW. 我不知道为什么您再次在服务器端发出消息。 I am assuming you are sending message from client to server. 我假设您正在从客户端向服务器发送消息。 So you shouldn't have emit command in your server code. 因此,您不应在服务器代码中包含发出命令。

If all the four things been fixed, it will work. 如果所有四个问题都已解决,那么它将起作用。

In case my expression is not clear, I wrote a super simple example for you: 如果我的表达不清楚,我为您写了一个超级简单的示例:

Server side: 服务器端:

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

Client side: 客户端:

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

My server code is written in typescript so never mind the let key word, double quote and so on. 我的服务器代码是用打字稿编写的,所以不要介意让关键字,双引号等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM