Communicating with sockets

Creating a listener TCP server socket

Report a typo

Your task is to build a Go program server.go with a listener TCP server socket that can handle multiple simultaneous client connections. Below is an initial code template for the server socket; your objective is to write the additional required code to:

  1. Set the constant values protocol = "tcp", address = "127.0.0.1", and port = ":12345".
  2. Initiate a listener TCP server socket using the above constants and ensure you defer closing it to release resources.
  3. Continuously listen and accept incoming client connection(s).
  4. Use a goroutine to handle each incoming client connection, allowing multiple simultaneous connections.
  5. Read the message from the client(s) and print it to the console.
  6. Send back to the client a fixed response message.
  7. Close each client connection after the interaction is completed.

DO NOT MODIFY the main() function; within it, the program will take a clientAmount and a message as input, and pass them to the hidden simulateClientsConnecting() function to start the process of multiple clients connecting.

Sample Input 1:

4
Hello, JetBrains Academy!

Sample Output 1:

Server socket is listening on 127.0.0.1:12345
Received from client: Hello, JetBrains Academy!
Received from client: Hello, JetBrains Academy!
Received from client: Hello, JetBrains Academy!
Received from client: Hello, JetBrains Academy!
Write a program in Go
// server.go

package main

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

// TODO: Set the protocol="tcp", address="127.0.0.1" and port=":12345" for the server socket:
const (
protocol = "?"
address = "127.0.0.1"
port = ":?"
bufferSize = 1024
)

func startServer() {
// TODO: Create a listener socket using the `protocol`, `address` and `port` constants:
connection, err := net.?(?, address+port)
if err != nil {
log.Println("cannot open server socket", err)
return
}
defer ? // TODO: Remember to `Close` the listener!
fmt.Printf("Server socket is listening on %s%s\n", address, port)

for {
connection, err := ? // TODO: `Accept` incoming client connection(s)
if err != nil {
log.Println("cannot accept client connection", err)
continue

Create a free account to access the full topic