JsonRPC/examples/Typescript/server.ts

77 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-07-21 16:33:23 +00:00
import * as net from "net";
import { Server, AddValueRequest, AddValueResponse, Test2 } from "./out";
2022-07-21 16:33:23 +00:00
import * as readline from 'node:readline';
const server = new Server.ServiceProvider();
class SimpleTestService extends Server.SimpleTestService<undefined> {
async GetTest(name: string, age: number, ctx: undefined): Promise<Test2> {
return {
name,
age,
};
}
TestNot(ctx: undefined): void {
}
}
2022-07-21 16:33:23 +00:00
class TestService extends Server.TestService<undefined> {
async AddValuesSingleParam(
request: AddValueRequest,
ctx: undefined
): Promise<AddValueResponse> {
return {
value: request.value1! + request!.value2!,
2022-07-21 16:33:23 +00:00
};
}
async AddValuesMultipleParams(
value1: number,
value2: number,
ctx: undefined
): Promise<number> {
return value1 + value2;
}
async ReturningVoid(param1) {
console.log("Calling Returning Void");
}
OnEvent(param1: string, ctx: undefined): void {
console.log("Received notification", param1);
}
async FunctionWithArrayAsParamAndReturn(vals1, vals2) {
return [...vals1, ...vals2];
}
async ThrowingError(ctx: undefined): Promise<void> {
throw new Error("Remote error!");
}
}
server.addService(new TestService());
server.addService(new SimpleTestService());
2022-07-21 16:33:23 +00:00
net.createServer((socket) => {
socket.on("error", console.error);
console.log("Connection from:", socket.remoteAddress);
const sess = server.getSession(msg => {
const s = JSON.stringify(msg);
console.log("Sending:", s);
socket.write(s + "\n");
});
const rl = readline.createInterface(socket);
rl.on("line", line => {
console.log("Receiving:", line);
sess.onMessage(JSON.parse(line));
})
rl.on("error", console.error);
}).listen(4321).on("listening", () => {
console.log("Is listening on :4321");
}).on("error", console.error)