一个最简单的WebSocket hello world demo
服务器端代码不超过42行:
const WSServer = require("./server.js"); var counter = 0; function createWebsocket() { var host = "127.0.0.1"; var port = "9999"; var wsServer = WSServer.startServer(host, port); console.log("WebSocket server listens to: " + host + ":" + port); wsServer.on('open', (data) => { console.log('WS Client has connected: ' + data); setInterval(function(){ counter++; WSServer.broadcast("Jerry: " + counter ); }, 3000); }); wsServer.on('dataWS', (data) => { console.log('Receive Data from WebUI : ' + data); }); wsServer.on('disconnect', (data) => { console.log('WSServer disconnect:' + data.name); }); wsServer.on('close', (data) => { console.log('WSServer close: ' + data.name); }); wsServer.on('end', (data) => { console.log('WSServer Close: '+data.name); }); wsServer.on('error', (data) => { }); } createWebsocket();
代码第10行创建一个WebSocket服务器,监听在9999端口上:
第15~18行每隔3秒发送一个字符串到浏览器,用一个计数器标识每次发送的请求。
代码里所需的server.js我已经上传到我的Github上了:
https://github.com/i042416/KnowlegeRepository/blob/master/practice/nodejs/server.js
使用nodejs启动这个服务器:
网页端代码:
<html> <script src="socket.io.dev.js"></script> <script> console.log("1"); var socket = io('ws://127.0.0.1:9999'); socket.on('connect', function(){ console.log("connected!"); }); socket.on('event', function(data){ console.log("event: " + data); }); socket.on('news', function(data){ console.log("data from server: " + JSON.stringify(data,2,2)); }); socket.on('disconnect', function(){ console.log("disconnect..."); }); </script> </html>
浏览器端每隔三秒收到服务器推送的消息,打印在console上:
要获取更多Jerry的原创文章,请关注公众号"汪子熙":
相关推荐
柳木木的IT 2020-11-04
joynet00 2020-09-23
wenf00 2020-09-14
蓝色深海 2020-08-16
wuychn 2020-08-16
取个好名字真难 2020-08-06
darylove 2020-06-26
shufen0 2020-06-20
Lovexinyang 2020-06-14
WangBowen 2020-06-14
firejq 2020-06-14
hjhmpl 2020-06-14
水痕 2020-06-07
guozewei0 2020-06-06
woniyu 2020-06-02
取个好名字真难 2020-06-01
guozewei0 2020-05-28
woniyu 2020-05-26