Kategorien
Allgemein

go tcp, go goroutine

My cloud server (hetzner cloud) shall get a tcp message and respond. Here is the example in go.

On the cloud server, run this go program:

# from https://dev.to/hgsgtk/how-go-handles-network-and-system-calls-when-tcp-server-1nbd

package main

import (
	"fmt"
	"net"
)

func main() {
	// Listen for incoming connections.
	addr := "localhost:8888"
	l, err := net.Listen("tcp", addr)
	if err != nil {
		panic(err)
	}
	// A defer statement postpones the execution of a function until the
        // surrounding function returns, either normally or through a panic.
	defer l.Close()
	fmt.Printf("Listening on %s\n", addr)

	for {
		// Listen for an incoming connection
		conn, err := l.Accept()
		if err != nil {
			panic(err)
		}
		// Handle connections in a new goroutine
		// To invoke function in a goroutine, use go f(s). 
                // the new goroutine will execute concurrently with the calling one.
		go func(conn net.Conn) {
			buf := make([]byte, 1024)
			len, err := conn.Read(buf)
			if err != nil {
				fmt.Printf("Error reading: %#v\n", err)
				return
			}
			fmt.Printf("Message received: %s\n", string(buf[:len]))

			conn.Write([]byte("Message received.\n"))
			conn.Close()
		}(conn)
	}
}

We can see, the server responds when sending something with nc or netcat, from the localhost:

root@node1:~# echo -n "Coming along locally..." | nc localhost 8888
Message received.

# firewall must be opened, port 8888 
# but still not working

echo -n "How's it going?" | nc -v $HETZNER1 8888
... 8888 (ddi-tcp-1): Connection refused

Besides allowing the port, we need to allow addresses other than localhost:

func main() {
	// Listen for incoming connections.
	addr := ":8888"
	l, err := net.Listen("tcp", addr)

# now working

go run tcpserver.go
Listening on :8888
Message received: I am coming from Christians Mac

echo "I am coming from Christians Mac " | netcat $HETZNER1 8888
static.xxx.xxx.xxx.xxx .clients.your-server.de [xxx.xxx.xxx.xxx] 8888 (ddi-tcp-1) open
Message received.