-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.js
50 lines (39 loc) · 1.16 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
let grpc = require("grpc");
var protoLoader = require("@grpc/proto-loader");
const server = new grpc.Server();
const SERVER_ADDRESS = "localhost:8080";
// Load protobuf
let proto = grpc.loadPackageDefinition(
protoLoader.loadSync("src/protos/chat.proto", {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
})
);
let users = [];
// Receive message from client joining
function join(call, callback) {
console.log(call)
users.push(call);
notifyChat({ user: "Server", text: "new user joined ..." });
}
// Receive message from client
function send(call, callback) {
console.log(call.request);
notifyChat(call.request);
console.log(callback)
return callback(null,{text:call.request.text})
}
// Send message to all connected clients
function notifyChat(message) {
users.forEach(user => {
user.write(message);
});
}
// Define server with the methods and start it
server.addService(proto.example.Chat.service, { join: join, send: send });
server.bind(SERVER_ADDRESS, grpc.ServerCredentials.createInsecure());
console.log("Start Server!");
server.start();