实现websocket长链接

1、nodejs代码

var ws = require("nodejs-websocket");
var PORT = 3001;

ws.createServer(function (req) {
    console.log("New connection", req);
    req.on("text", function (str) {
        console.log("Received " + str);
        // 返回消息
        req.sendText(str.toUpperCase() + "!!!");
    });
    req.on("close", function (code, reason) {
        // 关闭链接
        console.log("Connection closed");
    });
    req.on("error", function (err) {
        // 报错进这里
        console.log("handle err");
        console.log(err);
    });
})
.listen(PORT);

2、js代码

// 建立链接管道
const websocket = new WebSocket("ws://127.0.0.1:3001");
// 当WebSocket创建成功时,触发onopen事件
websocket.onopen = function () {
    console.log('websocket open');
    document.getElementById("recv").innerText = "Connected";
}
// 主动断开连接
websocket.onclose = function () {
    // 当客户端收到服务端发送的关闭连接请求时,触发onclose事件
    console.log('websocket close');
}
// 当客户端收到服务端发来的消息时,触发onmessage事件,参数e.data包含server传递过来的数据
websocket.onmessage = function (ev) {
    console.log(ev.data);
    document.getElementById("recv").innerHTML = ev.data;
}
//如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
 websocket.onerror = function(e){         
     console.log("websocket发生错误"+error);
}
document.getElementById("sendBtn").onclick = function () {
    let txt = document.getElementById("sendTxt").value;
    console.log(txt);
    //将消息发送到服务端
    websocket.send(txt);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值