EdgarAlejandro
EdgarAlejandro

Reputation: 367

What is the best way to keep a TCP server with GO listening?

I found this example 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()

}

echo "test" | nc 127.0.0.1 5555

What is the best way to keep a TCP server with GO listening in production? in localhost work fine but production

Upvotes: 2

Views: 1545

Answers (1)

hobbs
hobbs

Reputation: 239712

Taking out my crystal ball: I believe your problem is that your server is only listening on localhost, but you want to be able to connect to it from other machines. Change CONN_HOST from "localhost" to "" (empty string), so that net.Listen will be listening on :5555. That means that connections will be accepted on any interface on port 5555.

Upvotes: 3

Related Questions