Solution 3: Working with TCP/IP and WebSocket
Let’s solve the challenge set in the previous lesson.
We'll cover the following...
Solution
To run the client side for the concTCP.go TCP server, open a new terminal window and copy and paste the below command in it:
nc localhost 1234
Here’s an updated version of concTCP.go with signal handling. Execute the playground below and press “Ctrl + C” on the server side to stop the server.
package main
import (
"bufio"
"fmt"
"net"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
)
var count = 0
func handleConnection(c net.Conn) {
fmt.Print(".")
for {
netData, err := bufio.NewReader(c).ReadString('\n')
if err != nil {
fmt.Println(err)
return
}
temp := strings.TrimSpace(string(netData))
if temp == "STOP" {
break
}
fmt.Println(temp)
counter := "Client number: " + strconv.Itoa(count) + "\n"
c.Write([]byte(string(counter)))
}
c.Close()
}
func main() {
arguments := os.Args
if len(arguments) == 1 {
fmt.Println("Please provide a port number!")
return
}
PORT := ":" + arguments[1]
l, err := net.Listen("tcp4", PORT)
if err != nil {
fmt.Println(err)
return
}
defer l.Close()
// Handle SIGINT signal to gracefully shut down the server
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, syscall.SIGINT)
go func() {
<-sigint
fmt.Println("\n Received SIGINT signal, shutting down...")
l.Close()
os.Exit(0)
}()
for {
c, err := l.Accept()
if err != nil {
fmt.Println(err)
return
}
go handleConnection(c)
count++
}
}
concTCP.go
Code explanation
Line 14: This line declares a global variable count with an initial value of
0.Line 16: This ...
Ask