使用GO侦听保持TCP服务器的最佳方法是什么?
我找到了这个例子 回波“测试”| nc 127.0.0.1 5555 在生产中保持TCP服务器具有GO侦听功能的最佳方法是什么?使用GO侦听保持TCP服务器的最佳方法是什么?,go,tcp,Go,Tcp,我找到了这个例子 回波“测试”| nc 127.0.0.1 5555 在生产中保持TCP服务器具有GO侦听功能的最佳方法是什么? 在localhost中工作正常,但在生产中取出我的水晶球:我相信您的问题是您的服务器只在本地主机上侦听,但您希望能够从其他机器连接到它。将连接主机从本地主机更改为”(空字符串),以便net.Listen将侦听:5555。这意味着在端口5555上的任何接口上都可以接受连接。我使用“sudo$GOPATH/bin/tcp”运行go程序,但如何让它在后台运行我将CONN_主
在localhost中工作正常,但在生产中取出我的水晶球:我相信您的问题是您的服务器只在本地主机上侦听,但您希望能够从其他机器连接到它。将
连接主机
从本地主机
更改为”
(空字符串),以便net.Listen
将侦听:5555
。这意味着在端口5555上的任何接口上都可以接受连接。我使用“sudo$GOPATH/bin/tcp”运行go程序,但如何让它在后台运行我将CONN_主机从“localhost”更改为“ip_server”
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()
}