tcp server
# Node.js
const net = require("net");
function handler(socket) {
socket.write("Received: ");
socket.pipe(socket);
}
const server = net.createServer(handler);
server.listen(3000);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Output
$ echo 'hello' | nc localhost 3000
Received: hello
1
2
2
# Go
package main
import (
"bufio"
"net"
)
func handler(conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
return
}
conn.Write([]byte("Received: "))
conn.Write([]byte(message))
}
}
func main() {
listener, err := net.Listen("tcp", ":3000")
if err != nil {
panic(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
panic(err)
}
go handler(conn)
}
}
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
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
Output
$ echo 'hello' | nc localhost 3000
Received: hello
1
2
2
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22