Node.js-WebSocket节点模块:如何使多客户端套接字服务器正常工作?

奥基·伊利·里纳尔迪(Oki Erie Rinaldi)

我使用websocket模块创建了一个套接字服务器,此配置取自本示例(进行了一些更改):

    var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(5050, function() {
    console.log((new Date()) + ' Server is listening on port 5050');
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production 
    // applications, as it defeats all standard cross-origin protection 
    // facilities built into the protocol and the browser.  You should 
    // *always* verify the connection's origin and decide whether or not 
    // to accept it. 
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed. 
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin 
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }

    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

我在html中创建自己的客户端:

<html>
    <head>
        <script src='./js/jquery1-11-3-min.js'></script>
        <script>
            $(document).ready(function (){
                buildwebsocket();
            });
            var ws;
            function buildwebsocket(){
                ws = new WebSocket("ws://192.168.0.96:5050",'echo-protocol');
                ws.onopen = function(evt) { onOpen(evt) };
                ws.onclose = function(evt) { onClose(evt) };
                ws.onmessage = function(evt) { onMessage(evt) };
                ws.onerror = function(evt) { onError(evt) };
            }
            function onOpen(ev){
                //alert("konek men! mantap! :D");
                $("#recmsg").append("connected!<br>");
            }
            function onClose(ev){
                $("#recmsg").append("connection closed!<br>");
            }
            function onMessage(ev){
                //alert("ada pesan datang!");
                $("#recmsg").append(ev.data+"<br>");
            }
            function onError(ev){
                $("#recmsg").append("connecting error!<br>");
            }
            function doSend(){
                //writeToScreen("SENT: " + message); 
                var message = $("#pesan").val();
                ws.send(message);
            } function doClose(){
                ws.close();
            }
            //function writeToScreen(message){
                //var pre = document.createElement("p");
                //pre.style.wordWrap = "break-word";
                //pre.innerHTML = message;
                //output.appendChild(pre);
            //}
            //window.addEventListener("load", init, false);
        </script>
    </head>
    <body>
        <button onclick='doClose()'>Close</button>
        <textarea id='pesan'></textarea><br>
        <button onclick='doSend()'>Kirim!</button>
        <br>
        received message
        <div id='recmsg'>
        </div>  
    </body>
</html>

客户端(第一个客户端)与服务器之间的连接已成功建立。我尝试从第一个客户端发送消息,然后服务器接收到没有任何问题的消息,然后将消息发送回第一个客户端,第一个客户端接收它。我可以说连接和套接字都工作良好
我尝试建立另一个连接(第二个客户端),因此我在另一台设备中打开了第二个客户端。连接很好。但是,当我从第一个或第二个客户端发送消息时,第一个客户端没有得到响应,而第二个客户端得到了响应
而且,如果打开第三个客户端然后发送消息,则第一个和第二个客户端将无法获得响应。只有最后一个连接的客户端收到来自服务器的响应,并且没有客户端收到任何错误消息
这是模块缺点吗?还是必须更改/添加服务器配置?
我可以使用此模块建立多客户端支持的套接字服务器吗?

杰森

您没有将连接存储在服务器端。您只需在服务器上设置它们即可直接与服务器进行来回通信。如果希望将发往服务器的消息发送回所有人,则需要为.on('message', ...)服务器上的每个连接设置功能,以实现该行为。为此,您需要在创建连接时存储它们。尝试这个:

var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(5050, function() {
    console.log((new Date()) + ' Server is listening on port 5050');
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production 
    // applications, as it defeats all standard cross-origin protection 
    // facilities built into the protocol and the browser.  You should 
    // *always* verify the connection's origin and decide whether or not 
    // to accept it. 
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed. 
  return true;
}

//create an array to hold your connections
var connections = [];

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin 
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }
    var connection = request.accept('echo-protocol', request.origin);

    //store the new connection in your array of connections
    connections.push(connection);
    
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);

            //send the received message to all of the 
            //connections in the connection array
            for(var i = 0; i < connections.length; i++) {
                connections[i].sendUTF(message.utf8Data);
            }
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

套接字io,节点js,从服务器向客户端发送图像/文件的简单示例

如何在Angular / Node.js / Express中将客户端参数传递给服务器端

如何在Node.js服务器上的多个客户端之间同步数据

客户端中的关闭套接字使Node.js服务器崩溃

〜30秒后,Node.js“ ws” Websocket服务器随机断开客户端连接,错误1006

将前端本机Websocket客户端连接到Node.js Socket.io服务器

如何将通知从node.js服务器发送到android客户端。

如何最好地在Node.js中实现套接字客户端并中继到前端?

如何从Node.js服务器流到客户端

Node.js,如何在客户端退出后使服务器保持活动状态?

在Node.js / Express.js中,如何将JSON对象从服务器传输到客户端?

如何在Node.js中将文件从服务器发送到客户端

如何将jwt从swift客户端传递到node.js服务器

Socket.io Node Js服务器和React js客户端未连接

客户端无法连接到Azure应用服务上托管的Node.js Websocket服务器吗?

客户端js上的套接字服务器?

如何在Node.js中从客户端调用服务器端函数(例如html按钮onclick)?

服务器操作的Node.js客户端进度指示器

从服务器端在客户端获取变量(express.js,node.js)

Node.js服务器(移动客户端)

Node.js服务器的哪个Websocket库最适合iOS客户端?

如何在Node / Express中将JS从客户端移动到服务器?

Node.js多客户端处理

从Node JS Socket客户端向MINA套接字服务器发送消息

在node.js中从服务器端调用客户端函数

如何在Handlebars(客户端)中打印从Node JS服务器发送的JSON对象数组?

当服务器可能不可用时如何创建 Node.js Unix 套接字客户端

Node.js - 从服务器端还是客户端获取?

我在客户端使用 next.js 工作,在服务器端使用 node.js 表达