go - 让 TCP 服务器保持 GO 监听的最佳方法是什么?

标签 go tcp

我找到了这个例子https://play.golang.org/p/zyZJKGFfyT

package main

import (
    "fmt"
    "net"
    "os"
)

// echo "Hello server" | nc localhost 5555
const (
    CONN_HOST = "localhost"
    CONN_PORT = "5555"
    CONN_TYPE = "tcp"
)

func main() {
    // Listen for incoming connections.
    l, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT)
    if err != nil {
        fmt.Println("Error listening:", err.Error())
        os.Exit(1)
    }
    // Close the listener when the application closes.
    defer l.Close()
    fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
    for {
        // Listen for an incoming connection.
        conn, err := l.Accept()
        if err != nil {
            fmt.Println("Error accepting: ", err.Error())
            os.Exit(1)
        }
        // Handle connections in a new goroutine.
        go handleRequest(conn)
    }
}

// Handles incoming requests.
func handleRequest(conn net.Conn) {
  // Make a buffer to hold incoming data.
  buf := make([]byte, 1024)
  // Read the incoming connection into the buffer.
  reqLen, err := conn.Read(buf)
  reqLen = reqLen
  if err != nil {
    fmt.Println("Error reading:", err.Error())
  }
  // Send a response back to person contacting us.
  conn.Write([]byte("hello") )

  conn.Close()

}

回显“测试”|数控127.0.0.1 5555

在生产中保持 TCP 服务器与 GO 监听的最佳方法是什么? 在本地主机工作正常,但生产

最佳答案

拿出我的 Crystal 球:我相信您的问题是您的服务器仅在本地主机上监听,但您希望能够从其他计算机连接到它。将 CONN_HOST"localhost" 更改为 ""(空字符串),以便 net.Listen 将会监听在 :5555 上。这意味着端口 5555 上的任何接口(interface)上的连接都将被接受。

关于go - 让 TCP 服务器保持 GO 监听的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38387621/

相关文章:

Linux TCP : packet segmentation?

json - 解析 JSON 对象后打印选定字段时出错

dictionary - 迭代并从 map 中获取值

c# - 如何通过 TCP 通过 Internet 将 Motion JPEG 发送到 Windows Phone

windows - 如何提高高延迟网络上的 RPC 数据吞吐量

python - 如果 TCP 通信中丢失数据包,如何将客户端重新连接到服务器?

c++ - golang 中的 const 方法?

使用 map 中的值进行 map 搜索

mysql - Go 将非 ascii 形式的值保存为问号

linux - 每个 TCP/IP 网络连接的 Linux 内核消耗多少内存?