一个最简单的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

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

代码里所需的server.js我已经上传到我的Github上了:
https://github.com/i042416/KnowlegeRepository/blob/master/practice/nodejs/server.js

使用nodejs启动这个服务器:

 
一个最简单的WebSocket hello world demo

网页端代码:

<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上:

 
一个最简单的WebSocket hello world demo

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

 
一个最简单的WebSocket hello world demo

相关推荐