服务器端代码不超过 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/Kn…
使用 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 的原创文章,请关注公众号 ” 汪子熙 ”: