• Node极速开发WebSocket服务器


    1. 首先讲出核心代码index.js,如下:
    const crypto = require('crypto');
    const express = require('express');
    const { createServer } = require('http');
    const WebSocket = require('ws');
    
    const app = express();
    
    const server = createServer(app);
    const wss = new WebSocket.Server({ server });
    
    wss.on('connection', function(ws) {
      console.log("client joined.");
    
      // send "hello world" interval
      const textInterval = setInterval(() => ws.send("hello world!"), 100);
    
      // send random bytes interval
      const binaryInterval = setInterval(() => ws.send(crypto.randomBytes(8).buffer), 110);
    
      ws.on('message', function(data) {
        if (typeof(data) === "string") {
          // client sent a string
          console.log("string received from client -> '" + data + "'");
    
        } else {
          console.log("binary received from client -> " + Array.from(data).join(", ") + "");
        }
      });
    
      ws.on('close', function() {
        console.log("client left.");
        clearInterval(textInterval);
        clearInterval(binaryInterval);
      });
    });
    
    server.listen(8080, function() {
      console.log('Listening on http://localhost:8080');
    });
    

    1. 其次,讲明使用的库,写入packages.json文件中,如下:
    {
      "name": "nodeserver",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "start": "node index.js",
        "test": "echo "Error: no test specified" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "express": "^4.17.1",
        "ws": "^7.1.2"
      }
    }
    

    1. 最后,执行即可,先npm install安装依赖包,再执行npm run start或直接执行node index.js

    1. 基于Node.js的WebSocket极简服务器开发完成。




    作者:艾孜尔江

  • 相关阅读:
    系统分析师考试
    系统分析师
    软件设计师考试
    海恩法则”的启示:制度不落到实处事故必发
    eclipse下生成Java类图和时序图,生成UML图
    bzoj4010【HNOI2015】菜肴制作
    atitit.提升开发效率---MDA 软件开发方式的革命(5)----列表查询建模
    【数据结构和算法16】堆排序
    这一路走来,冷暖自知 (附算法demos)
    c++实现二叉搜索树
  • 原文地址:https://www.cnblogs.com/ezhar/p/14329222.html
Copyright © 2020-2023  润新知