默认
打赏 发表评论 23
想开发IM:买成品怕坑?租第3方怕贵?找开源自已撸?尽量别走弯路了... 找站长给点建议
引用:LanjunLi 发表于 2023-05-25 10:02
nodejs-websocket 包在客户端关闭时会导致服务器端发生异常而退出。

什么样的异常,有异常信息吗
Nodejs 服务端代码:
let ws = require("nodejs-websocket");
let server = ws.createServer((conn) => {
  console.log("new connection");
  conn.on("text", (msg) => {
    broadcast(server, msg);
  });

  conn.on("close", () => {
    console.log("connection closed");
  });
});

function broadcast(server, msg) {
  server.connections.forEach((conn) => {
    conn.sendText(msg);
  });
}
server.listen(3001)


客户端代码:
  
const ws = new WebSocket("ws://127.0.0.1:3001");
    ws.onopen = function () {
        oUl.innerHTML += "<li>客户端链接成功</li>";
        oSend.onclick = function () {
            if (!/^\s*$/.test(oText.value)) {
                ws.send(oText.value);
            }
        };

    };
    ws.onmessage = function (msg) {
        oUl.innerHTML += `<li>${msg.data}</li>`;
    };
    ws.onclose = function () {
        oUl.innerHTML += "<li>客户端链接断开</li>";
    }


当浏览器刷新客户端端页面时,服务端报出以下错误信息
connection closed
Uncaught Error: read ECONNRESET
  __node_internal_captureLargerStackTrace	
  __node_internal_errnoException	
  onStreamRead	
  callbackTrampoline	
Async call from TickObject
  init	
  emitInitNative	
  emitInitScript	
  nextTick	
  onDestroy	
  Socket._destroy	
  _destroy	
  destroy	
  onStreamRead	
  callbackTrampoline	
Async call from TCPWRAP
  init	
  emitInitNative	

签名: 学习中
nodejs话,就用socket.io吧,这是最好的,别用其它那些野鸡websocket库了
我也只是看到这篇文章的代码,拿来实验一下。建议把这块有问题的代码移除。
签名: 学习中
打赏楼主 ×
使用微信打赏! 使用支付宝打赏!

返回顶部