图片授权基于:www.pixabay.com 相关协议
ws 是协议标识符(如果加密,则为wss),后面跟上服务器的地址。
let websocket = new WebSocket(\\\"wss://服务器地址\\\");
websocket.onopen = function() {
websocket.send(\\\"Hello WebSocket\\\");
};
websocket.onmessage = function(data) {
console.log(data.data);
};
websocket.onerror = function() {
console.log(\\\"出现错误...\\\");
}
websocket.onclose = function() {
console.log(\\\"连接关闭...\\\");
}
let websocket = new WebSocket(\\\"wss://服务器地址\\\");
websocket.onopen = function(evt) {
websocket.send(\\\"连接成功,发送个消息。\\\");
};
websocket.onmessage = function(data) {
console.log(\\\"获取到数据\\\");
};
websocket.onerror = function() {
console.log(\\\"出现错误\\\");
};
websocket.onclose = function() {
console.log(\\\"连接关闭\\\");
};
var timer;
var startFn = function() {
var ws = new WebSocket(\\\'ws://localhost:3000\\\');
ws.onmessage = function(mes) {
console.log(mes.data);
clearTimeout(timer);//清除计时
timerFn();//开始计时
};
//错误,需要重新发起请求
ws.onerror = function(mes) {
clearTimeout(timer);
timerFn();//重新发起请求
};
};
var timerFn = function() {
timer = setTimeout(function() {
startFn();//重新发起请求
}, 45000);
};
startFn()
const WebSocket = require(\\\'ws\\\');
const WebSocketServer = WebSocket.Server;
//创建 websocket 服务器 监听在 3000 端口
const wss = new WebSocketServer({port: 3000});
// 服务器被客户端连接
wss.on(\\\'connection\\\', function(ws) {
// 接收客户端信息并把信息返回发送
ws.on(\\\'message\\\', function(message) {
ws.send(message + \\\' 客户端消息\\\');
});
var senFn = function() {
ws.send(Math.round(Math.random() * 10));
setTimeFn();
};
var setTimeFn = function() {
setTimeout(function() {
senFn();
},40000);
};
setTimeFn();
});
项目 Git 地址
git@github.com:cuishunbiao/websocket.git
推荐阅读
为什么「局部变量」访问速度快
原创文章,作者:小道研究,如若转载,请注明出处:https://www.sudun.com/ask/34595.html