网络营销机构官方网站,网站建设项目内控单,做国际贸易网站哪家好,做seo网站 公司webScoket是什么#xff1f; 支持端对端通讯可以由客户端发起#xff0c;也可以有服务端发起用于消息通知、直播间讨论区、聊天室、协同编辑等 做一个简单的webScoket 客户端配置#xff1a;
1、新建一个页面叫web-scoket.html !DOCTYPE html
html lang… webScoket是什么 支持端对端通讯可以由客户端发起也可以有服务端发起用于消息通知、直播间讨论区、聊天室、协同编辑等 做一个简单的webScoket 客户端配置
1、新建一个页面叫web-scoket.html !DOCTYPE html
html langen
headmeta charsetUTF-8meta nameviewport contentwidthdevice-width, initial-scale1.0titlewebScoket/title
/head
bodypwebScoket/pbutton idbtn-send发送消息/buttonscriptconst btnSend document.getElementById(btn-send)/script
/body
/html 服务器端配置
1、进入一个目录执行npm init -y
注意执行以上命令会生成一个package.json的文件 {name: web-scoket-sever,version: 1.0.0,description: ,main: index.js,scripts: {test: echo \Error: no test specified\ exit 1},keywords: [],author: ,license: ISC
}2、安装ws和nodemon插件、以下是安装插件的命令
sudo cnpm i ws
sudo cnpm i nodemon
3、在文件夹下新建一个src目录在src目录下新建index.js文件 const { WebSocketServer } require(ws)//new 一个webScoket服务端口号为3000
const wsServer new WebSocketServer({ port: 3000 })//监听连接connection
wsServer.on(connection, wx {console.info(connection);//监听信息msg客户端传递过来的信息wx.on(message, msg {console.info(收到信息, msg);//收到信息2秒后给客户端一个反馈setTimeout(() {//we.send给客户端发送信息we.send(服务端已收到信息 msg.toString())}, 2000)})
})
4、修改package.json文件中的代码 dev: nodemon src/index.js
5、代码执行npm run dev启动服务