...

/

Solution 5: Working with TCP/IP and WebSocket

Solution 5: Working with TCP/IP and WebSocket

Let’s solve the challenge set in the previous lesson.

We'll cover the following...

Solution

Here is an example of a WebSocket server that creates a variable number of random integers that are sent to the client.

To run the client side, open a new terminal window and copy and paste the below commands:

Press + to interact
# Set the environment variables for executing Go commands:
export GOROOT=/usr/local/go; export GOPATH=$HOME/go; export PATH=$GOPATH/bin:$GOROOT/bin:$PATH;
# Change directory to usercode:
cd usercode
# Execute the client to see the output:
go run client.go

The following playground contains server (ws.go) and client (client.go) code files:

package main

import (
	"fmt"
	"log"
	"net/url"

	"github.com/gorilla/websocket"
)

func main() {
	u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/"}
	conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("Error connecting to WebSocket:", err)
	}
	defer conn.Close()

	// Send initial message to server
	message := struct {
		Count int `json:"count"`
	}{Count: 10} // Request 10 random integers
	err = conn.WriteJSON(&message)
	if err != nil {
		log.Fatal("Error sending initial message to WebSocket:", err)
	}
    fmt.Println("Requested 10 random numbers from the server")
    fmt.Println("Received random integers:")

	// Receive random integers from server
	for i := 0; i < message.Count; i++ {
		var integer int
		err = conn.ReadJSON(&integer)
		if err != nil {
			log.Fatal("Error receiving random integer from WebSocket:", err)
		}
		fmt.Println(integer)
	}
}
ws.go & client.go

Code explanation

Here is the code explanation for ws.go:

  • Line 11: The upgrader ...