一个最简单的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端口上:

一个最简单的WebSocket hello world demo_第1张图片

第15~18行每隔3秒发送一个字符串到浏览器,用一个计数器标识每次发送的请求。

代码里所需的server.js我已经上传到我的Github上了:

https://github.com/i042416/KnowlegeRepository/blob/master/practice/nodejs/server.js

使用nodejs启动这个服务器:

网页端代码:





浏览器端每隔三秒收到服务器推送的消息,打印在console上:

一个最简单的WebSocket hello world demo_第2张图片

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

你可能感兴趣的:(一个最简单的WebSocket hello world demo)