2016-07-15 60 views
1

我發現這個例子https://play.golang.org/p/zyZJKGFfyT保持與GO聽TCP服務器的最佳方式是什麼?

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() 

} 

回聲 「測試」 | nc 127.0.0.1 5555

在生產中監聽GO服務器的最佳方式是什麼? 在本地主機工作正常,但生產

回答

2

拿出我的水晶球:我相信你的問題是你的服務器只在本地主機上監聽,但你希望能夠從其他機器連接到它。將CONN_HOST"localhost"更改爲""(空字符串),以便net.Listen將在:5555上收聽。這意味着連接將在任何接口端口被接受5555

+0

我與「須藤$ GOPATH /斌/ TCP」,但我如何讓它在backgrount – EdgarAlejandro

+0

我改變CONN_HOST從「localhost」的都跑了圍棋程序到「ip_server」 – EdgarAlejandro

相關問題