How to create a TCP Server in Go

The net package provide a very easy and abstract way to create TCP server in Go.

Server

We can use the net.Listen() function to generate a listener, and call Accept() method on that listener to accept connections. We can also use /encoding/gob package to Encode messages we want to send, and Decode messages that are coming to out Server.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main

import (
	"encoding/gob"
	"fmt"
	"net"
)

// Handler to deal with connections
func connectionHandler(c net.Conn) {
	var msg string
	// Encoding coming message
	err := gob.NewDecoder(c).Decode(&msg)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Message Received: ", msg)
	}
	// Close connection after finsihing reading message
	c.Close()
}

func server() {
	// crreate a listener on port 8080 using tcp protocol
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		fmt.Println(err)
		return
	}
	for {
		// Accept coming connection
		c, err := listener.Accept()
		if err != nil {
			fmt.Println(err)
			continue
		}
		// using goroutine to handle connection
		go connectionHandler(c)
	}
}

func main() {
	server()
}

Client

This example will send the “Hello” message to our server (localhost:8080) for every 3 seconds

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
	"encoding/gob"
	"fmt"
	"net"
	"time"
)

func client() {
	// Make a connect to localhost at 8080 port, with tcp protocol
	c, err := net.Dial("tcp", "127.0.0.1:8080")
	if err != nil {
		fmt.Println(err)
		return
	}
	msg := "Hello!"
	// Encode the message and send through the connect
	err = gob.NewEncoder(c).Encode(msg)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Sent: ", msg)
	c.Close()
}

func main() {
	for i := 0; i < 3; i++ {
		client()
		// Wait 3 seconds before next attempt
		time.Sleep(3 * time.Second)
	}
}