udp server
# Node.js
const dgram = require("dgram");
const server = dgram.createSocket("udp4");
server.on("error", (err) => {
console.error(err);
server.close();
});
server.on("message", (msg, rinfo) => {
const data = msg.toString("utf8").trim();
console.log(`received: ${data} from ${rinfo.address}:${rinfo.port}`);
});
server.on("listening", () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind(3000);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Output
$ echo 'hello world' > /dev/udp/0.0.0.0/3000
server listening 0.0.0.0:3000
received: hello world from 127.0.0.1:51452
1
2
3
4
2
3
4
# Go
package main
import (
"fmt"
"net"
"strings"
)
func main() {
conn, err := net.ListenUDP("udp", &net.UDPAddr{
Port: 3000,
IP: net.ParseIP("0.0.0.0"),
})
if err != nil {
panic(err)
}
defer conn.Close()
fmt.Printf("server listening %s\n", conn.LocalAddr().String())
for {
message := make([]byte, 20)
rlen, remote, err := conn.ReadFromUDP(message[:])
if err != nil {
panic(err)
}
data := strings.TrimSpace(string(message[:rlen]))
fmt.Printf("received: %s from %s\n", data, remote)
}
}
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
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
Output
$ echo 'hello world' > /dev/udp/0.0.0.0/3000
server listening [::]:3000
received: hello world from 127.0.0.1:50275
1
2
3
4
2
3
4
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22