-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
94 lines (80 loc) · 2.41 KB
/
client.js
File metadata and controls
94 lines (80 loc) · 2.41 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const path = require('path');
const readline = require('readline'); // For user input
// Load the protobuf definition
const PROTO_PATH = path.join(__dirname, 'chat.proto');
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
});
const chat_proto = grpc.loadPackageDefinition(packageDefinition).chat;
// Create a gRPC client
const client = new chat_proto.ChatService('localhost:50051', grpc.credentials.createInsecure());
// Set up readline for user input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let userName = '';
// Function to start the chat
function startChat() {
console.log(`Welcome to the gRPC Chat! Your name: ${userName}`);
console.log('Type your message and press Enter. Type "exit" to quit.');
const call = client.Chat(); // Initiate the bidirectional stream
// Handle incoming messages from the server
call.on('data', (message) => {
const date = new Date(Number(message.timestamp));
console.log(`\n[${message.sender} - ${date.toLocaleTimeString()}]: ${message.message}`);
rl.prompt(true); // Re-prompt after receiving a message
});
call.on('end', () => {
console.log('Server stream ended.');
rl.close();
process.exit();
});
call.on('error', (err) => {
console.error('Stream error:', err.message);
rl.close();
process.exit(1);
});
call.on('status', (status) => {
console.log('Stream status:', status);
});
// Handle outgoing messages from user input
rl.on('line', (line) => {
if (line.toLowerCase() === 'exit') {
call.end(); // End the client's side of the stream
rl.close();
return;
}
if (line.trim() !== '') {
const chatMessage = {
sender: userName,
message: line.trim(),
};
call.write(chatMessage);
}
rl.prompt(true); // Prompt again for the next message
});
rl.prompt(true);
}
// Ask for the user's name before starting the chat
rl.question('Please enter your name: ', (name) => {
userName = name.trim();
if (userName === '') {
console.log('Name cannot be empty. Exiting.');
rl.close();
process.exit(1);
} else {
startChat();
}
});
process.on('SIGINT', () => {
console.log('\nExiting chat...');
rl.close();
process.exit();
});