Go’s net
package holds everything you need to work with protocols like TCP, UDP and HTTP.
Therefore, Go is a sollid choice for building networking applications.
l, err := net.Listen("tcp", "0.0.0.0:6379")
if err != nil {
fmt.Println("Failed to bind to port 6379")
os.Exit(1)
}
Accepting TCP connections:
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting connection: ", err.Error())
os.Exit(1)
}
Data from packages the server received can be read like this:
for {
buf := make([]byte, 1024)
_, err := conn.Read(buf)
if err != nil {
fmt.Println("Error reading: ", err.Error())
break
}
fmt.Println("Received: ", string(buf))
}
Data can be send by writing to the connection:
_, err = conn.Write([]byte("+PONG\r\n"))
if err != nil {
fmt.Println("Error writing: ", err.Error())
break
}