ZBLOG

golang dail tcp

To create a TCP server in Go, you can use the net package.

Here’s an example of creating a simple TCP server:

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. )
  6. func main() {
  7. // listen on port 8080
  8. ln, err := net.Listen("tcp", ":8080")
  9. if err != nil {
  10. fmt.Println(err)
  11. return
  12. }
  13. defer ln.Close()
  14. fmt.Println("TCP server listening on :8080")
  15. for {
  16. // wait for a connection
  17. conn, err := ln.Accept()
  18. if err != nil {
  19. fmt.Println(err)
  20. continue
  21. }
  22. // handle the connection in a separate goroutine
  23. go handleConnection(conn)
  24. }
  25. }
  26. func handleConnection(conn net.Conn) {
  27. defer conn.Close()
  28. // read from the connection
  29. buf := make([]byte, 1024)
  30. _, err := conn.Read(buf)
  31. if err != nil {
  32. fmt.Println(err)
  33. return
  34. }
  35. // echo back to the client
  36. conn.Write(buf)
  37. }

In this example, we’re listening on port 8080 for incoming TCP connections. When a connection is accepted, we spawn a new goroutine to handle it. The handleConnection() function reads from the connection and echoes the data back to the client.

To test this server, you can use the telnet command:

  1. $ telnet localhost 8080
  2. Trying 127.0.0.1...
  3. Connected to localhost.
  4. Escape character is '^]'.
  5. hello, world!
  6. hello, world!
  7. Connection closed by foreign host.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=728

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?