tcp server


Node.js

  1. const net = require('net')
  2. function handler(socket) {
  3. socket.write('Received: ')
  4. socket.pipe(socket)
  5. }
  6. const server = net.createServer(handler)
  7. server.listen(3000)

Output

  1. $ echo 'hello' | nc localhost 3000
  2. Received: hello

Go

  1. package main
  2. import (
  3. "bufio"
  4. "net"
  5. )
  6. func handler(conn net.Conn) {
  7. defer conn.Close()
  8. reader := bufio.NewReader(conn)
  9. for {
  10. message, err := reader.ReadString('\n')
  11. if err != nil {
  12. return
  13. }
  14. conn.Write([]byte("Received: "))
  15. conn.Write([]byte(message))
  16. }
  17. }
  18. func main() {
  19. listener, err := net.Listen("tcp", ":3000")
  20. if err != nil {
  21. panic(err)
  22. }
  23. defer listener.Close()
  24. for {
  25. conn, err := listener.Accept()
  26. if err != nil {
  27. panic(err)
  28. }
  29. go handler(conn)
  30. }
  31. }

Output

  1. $ echo 'hello' | nc localhost 3000
  2. Received: hello