ts+ws+protobuf

本文展示了如何通过npm安装ws、protobufjs相关类型定义,以及如何编译.proto文件为JS模块。接着,创建了一个WebSocket服务器监听8083端口,接收并处理客户端发送的HelloRequest消息,同时给出了客户端连接到服务器并发送消息的示例。
摘要由CSDN通过智能技术生成

安装

npm install ws @types/ws protobufjs @types/protobufjs protobufjs-cli

helloworld.proto

syntax = "proto3";

package helloworld;

message HelloRequest {
  string name = 1;
  string id = 2;
  string head = 3;
  int32 age = 4;
}

编译proto文件成js文件

pbjs -t static-module -w commonjs -o helloworld.js helloworld.proto
pbts -o helloworld.d.ts helloworld.js

ws_server.ts

import { WebSocketServer } from "ws";
import { helloworld } from "helloworld";

const server = new WebSocketServer({ port: 8083 });
server.on("listening", () => {
    console.log("listening!");
});

server.on("connection", function connection(ws) {
    ws.on("message", function incoming(message) {
        console.log("received:%s", message);

        let u = helloworld.HelloRequest.decode(<Uint8Array>message);

        console.log(`server:${u.id},${u.name}`);

        let sendData = helloworld.HelloRequest.create();
        sendData.name = "server";
        sendData.id = "0"
        ws.send(helloworld.HelloRequest.encode(sendData).finish());
    });
});

ws_client.ts

import { WebSocket } from "ws";
import { helloworld } from "helloworld";

const client = new WebSocket("ws://localhost:8083");


client.on("open", () => {
    let sendData = helloworld.HelloRequest.create();
    sendData.name = "client";
    sendData.id = "1000001"
    client.send(helloworld.HelloRequest.encode(sendData).finish());
});


client.on("message", function incoming(message) {
    console.log("received:%s", message);

    let u = helloworld.HelloRequest.decode(<Uint8Array>message);
    console.log(`client:${u.id},${u.name}`);
});

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值