安装
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}`);
});