create a tcp server on a specific port in go

To create a TCP server in Go, you can use the net package. Here is an example of creating a TCP server on a specific port:

main.go
package main

import (
    "fmt"
    "net"
)

func main() {
    port := ":8080" // Replace 8080 with the port you want to use

    // Listen for incoming connections on the specified port
    listener, err := net.Listen("tcp", port)
    if err != nil {
        fmt.Println("Error listening:", err.Error())
        return
    }

    defer listener.Close()

    fmt.Println("Listening on port", port)

    // Loop indefinitely to accept incoming connections
    for {
        // Accept a new client connection
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("Error accepting:", err.Error())
            return
        }

        // Handle the client connection in a separate goroutine
        go handleClient(conn)
    }
}

func handleClient(conn net.Conn) {
    defer conn.Close()

    // Do something with the client connection
}
869 chars
41 lines

In the main() function, we call net.Listen() to create a TCP listener on the specified port. We then loop indefinitely using a for loop and call listener.Accept() to accept incoming client connections. For each incoming connection, we launch a new goroutine by calling the handleClient() function.

In the handleClient() function, we pass in the client connection as an argument to the function. We can then perform any actions we want to handle the client connection. In this example, we simply close the connection after handling it.

Note: Don't forget to handle potential errors when setting up and running your TCP server.

related categories

gistlibby LogSnag