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)
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
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)
}
}
Output
$ echo 'hello world' > /dev/udp/0.0.0.0/3000
server listening [::]:3000
received: hello world from 127.0.0.1:50275
当前内容版权归 miguelmota 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 miguelmota .