...

/

Solution 2: Working with TCP/IP and WebSocket

Solution 2: Working with TCP/IP and WebSocket

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

We'll cover the following...

Solution

Here is the concurrent TCP server (concTCP.go) that generates random numbers in a range that is given by the TCP client.

To run the client side, open a new terminal window and copy and paste the command below into it.

nc localhost 1234

The following playground contains the concurrent TCP server (concTCP.go) code:

package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"net"
	"strconv"
	"strings"
	"time"
)

func handleConnection(conn net.Conn) {
    defer conn.Close()
    r := bufio.NewReader(conn)
    for {
        fmt.Fprint(conn, ">> Enter a number or 'quit' to quit \n")

        line, err := r.ReadString('\n')
        if err != nil {
            break
        }
        line = strings.TrimSpace(line)
        if line == "quit" {
            break
        }
        n, err := strconv.Atoi(line)
        if err != nil {
            fmt.Println("Invalid number")
            continue
        }
        fmt.Println("Generating random number in range 0 to", n)
        rand.Seed(time.Now().UnixNano())
        fmt.Fprintln(conn, "Random number generated:", rand.Intn(n))
    }
}


func main() {
	ln, err := net.Listen("tcp", ":1234")
	if err != nil {
		panic(err)
	}
	defer ln.Close()
	for {
		conn, err := ln.Accept()
		if err != nil {
			panic(err)
		}
		go handleConnection(conn)
	}
}
concTCP.go

Code explanation

  • Lines 13–15: The handleConnection ...