This repository was archived by the owner on Aug 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1-socket.ts
More file actions
45 lines (36 loc) · 1.27 KB
/
1-socket.ts
File metadata and controls
45 lines (36 loc) · 1.27 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
import { createServer, Server, Socket } from "net";
const port: number = 9903;
// ---------------------------------------------
// server
// ---------------------------------------------
const server: Server = createServer((clientSocket: Socket) => {
// 2. this is the client below
console.log(
`[server] connected client: ${JSON.stringify(clientSocket.address())}`
);
clientSocket.on("data", (clientData) => {
// 4. receive data from client
console.log(`[server] received data from client: ${clientData}`);
clientSocket.write(`~~echo~~ ${clientData.toString()}\r\n`); // 5. send data to client
});
});
server.listen(port, () => {
console.log(`[server] opened server: ${JSON.stringify(server.address())}`);
});
// ---------------------------------------------
// client
// ---------------------------------------------
const client: Socket = new Socket();
client.connect(port, "127.0.0.1", () => {
// 1. connect to server
console.log(`[client] connected`);
client.write("hello world!"); // 3. send data to server
});
client.on("data", (serverData) => {
// 6. receive data from server
console.log(`[client] received data from server: ${serverData}`);
client.destroy();
});
client.on("close", () => {
console.log(`[client] connection closed`);
});