udp server


Node.js

  1. const dgram = require('dgram')
  2. const server = dgram.createSocket('udp4')
  3. server.on('error', err => {
  4. console.error(err)
  5. server.close()
  6. })
  7. server.on('message', (msg, rinfo) => {
  8. const data = msg.toString('utf8').trim()
  9. console.log(`received: ${data} from ${rinfo.address}:${rinfo.port}`)
  10. })
  11. server.on('listening', () => {
  12. const address = server.address()
  13. console.log(`server listening ${address.address}:${address.port}`)
  14. })
  15. server.bind(3000)

Output

  1. $ echo 'hello world' > /dev/udp/0.0.0.0/3000
  2. server listening 0.0.0.0:3000
  3. received: hello world from 127.0.0.1:51452

Go

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "strings"
  6. )
  7. func main() {
  8. conn, err := net.ListenUDP("udp", &net.UDPAddr{
  9. Port: 3000,
  10. IP: net.ParseIP("0.0.0.0"),
  11. })
  12. if err != nil {
  13. panic(err)
  14. }
  15. defer conn.Close()
  16. fmt.Printf("server listening %s\n", conn.LocalAddr().String())
  17. for {
  18. message := make([]byte, 20)
  19. rlen, remote, err := conn.ReadFromUDP(message[:])
  20. if err != nil {
  21. panic(err)
  22. }
  23. data := strings.TrimSpace(string(message[:rlen]))
  24. fmt.Printf("received: %s from %s\n", data, remote)
  25. }
  26. }

Output

  1. $ echo 'hello world' > /dev/udp/0.0.0.0/3000
  2. server listening [::]:3000
  3. received: hello world from 127.0.0.1:50275