先来吐槽一下,想要找点技术文章真tm不容易,全是jb复制粘贴,还冒充原创。搜索一个ws实现websocket全是一样的。一个字都没变,我能说什么。最后想到搜索ws模块githup居然前两页没有,也是那些重复的文章,无力吐槽。奉上一个githup上面的(虽然全是英文的,但是绝壁比那些复制粘贴的好)
https://github.com/websockets/ws#broadcast-example
需要安装express模块、ws模块
客户端代码:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>在线聊天</title> </head> <body> <input type="text" onblur="wsServer.onopen(this.value)"> <script> var wsServer = new WebSocket('ws://127.0.0.1:8000'); wsServer.onopen = function (e) { (typeof e == 'string') && wsServer.send(e);//向后台发送数据 }; wsServer.onclose = function (e) {//当链接关闭的时候触发 }; wsServer.onmessage = function (e) {//后台返回消息的时候触发 console.log(e); }; wsServer.onerror = function (e) {//错误情况触发 } </script> </body> </html>
写的很简单,反正能运行就行。更多内容点击:meetqy