TCP 全双工通讯协议
即时通信
场景: 聊天、消息系统、游戏
web: 消息通知、大屏项目的数据更新、商家推荐
实现:
1.握手 客户端连接服务端(认识一下)
let client = new WebSocket(“ws://localhost:3000”);
2.建立连接之后 互发消息
发送
client.send(“hello”)//向服务端发送信息
client.send(JSON.stringify({
to:“123”,
msg:“hello”
}))
接收
client.addEventListener(“message”,({data})=>{
console.log(data);
})
3.连接关闭
client.addEventListener(“open”,()=>{
console.log(“连接成功”)
})
client.addEventListener(“close”,()=>{
console.log(“断开连接”)
})
客户端主动断开连接
client.close();
server.js
var webSocket = require(“ws”);
// 创建socket服务
var wss = new webSocket.Server({ port: 5000 });
// var clients=[];
// 监听客户端连接事件
wss.on(“connection”, function (client) {
// 向客户端发送信息
client.send(“服务端已连接”);
// 接收客户端消息
client.on(“message”, function (msg) {
// console.log(e.data);
client.send(“接收到你发的消息:” + msg);
});
setInterval(function () {
client.send(Date.now());
}, 1000);
// 监听客户端关闭连接操作
client.on(“close”, function () {
console.log(“客户端关闭连接”);
});
});
server02.js
var webSocket = require(“ws”);
// 创建socket服务
var wss = new webSocket.Server({ port: 5001 });
// var clients=[];
// 监听客户端连接事件
wss.on(“connection”, function (client) {
client.on(“message”, function (data) {
// 群发 广播
// wss.clients所有的客户端对象
wss.clients.forEach(function (item) {
item.send(data);
});
});
});
/*
{
type:“login”
}
{
type:"room",
roomId:"1",
msg:"hello"
}
{
type:"person",
to:"张三",
msg:"hello"
}
*/
基本使用.html
广播.html
发布广播.html
普通用户.html