To create a TCP server in Go, you can use the net
package.
Here’s an example of creating a simple TCP server:
package main
import (
"fmt"
"net"
)
func main() {
// listen on port 8080
ln, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println(err)
return
}
defer ln.Close()
fmt.Println("TCP server listening on :8080")
for {
// wait for a connection
conn, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
}
// handle the connection in a separate goroutine
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
// read from the connection
buf := make([]byte, 1024)
_, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
return
}
// echo back to the client
conn.Write(buf)
}
In this example, we’re listening on port 8080 for incoming TCP connections. When a connection is accepted, we spawn a new goroutine to handle it. The handleConnection()
function reads from the connection and echoes the data back to the client.
To test this server, you can use the telnet
command:
$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hello, world!
hello, world!
Connection closed by foreign host.