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:
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)
}
}Code explanation
Here is the code explanation for socketServer.go:
Line 11: We define a function called
echothat takes a singlecargument of typenet.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: ...