Search⌘ K
AI Features

Solution 4: Working with TCP/IP and WebSocket

Explore how to implement TCP/IP and UNIX domain socket communication along with WebSocket server and client creation in Go. Learn to write and run socket servers and clients, handle connections, and manage data transmission using Go’s networking libraries. This lesson provides practical experience with network socket programming concepts vital for concurrent system development.

We'll cover the following...

Solution

In this lesson, we will write a UNIX domain socket server (socketServer.go) that generates random numbers and socketClient.go code.

To run the client side for the socketServer.go server, open a new terminal window and copy and paste the below commands into it:

Shell
# Set the environment variables for the Go programming language:
export GOROOT=/usr/local/go; export GOPATH=$HOME/go; export PATH=$GOPATH/bin:$GOROOT/bin:$PATH;
# Change directory to usercode:
cd usercode
# Command to run the client:
go run socketClient.go /tmp/packt.socket

Execute the server and client sides in the following playground:

package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
	"time"
)

func main() {
	// Read socket path
	if len(os.Args) == 1 {
		fmt.Println("Need socket path")
		return
	}
	socketPath := os.Args[1]

	c, err := net.Dial("unix", socketPath)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer c.Close()

	for {
		fmt.Print(">> ")
		reader := bufio.NewReader(os.Stdin)
		text, _ := reader.ReadString('\n')

		_, err = c.Write([]byte(text))
		if err != nil {
			fmt.Println("Write:", err)
			break
		}

		buf := make([]byte, 256)

		n, err := c.Read(buf[:])
		if err != nil {
			fmt.Println(err, n)
			return
		}
		fmt.Print("\n Random numbers generated are: ", string(buf[0:n]))

		fmt.Print("\n")
		if strings.TrimSpace(string(text)) == "STOP" {
			fmt.Println("\n Exiting UNIX domain socket client!")
			return
		}

		time.Sleep(5 * time.Second)
	}
}
socketServer.go & socketClient.go

Code explanation

Here is the code explanation for socketServer.go:

  • Line 11: We define a function called echo that takes a single c argument of type net.Conn. This function will be called for each client that connects to the server.

  • Line 13: This line seeds the random number generator with the current time so that the sequence of random numbers generated will be different every time the program is run.

  • Line 14: ...