79342617

Date: 2025-01-09 12:40:17
Score: 1
Natty:
Report link

I came up with this:

package main

import (
    "fmt"
    "io"
    "net"
    "os"
)


func main() {
    var userChoice int

    fmt.Printf("Listen[1] or Connect[0]?")
    fmt.Scan(&userChoice)
    if userChoice == 1 {
        listen()
    } else if userChoice == 0 {
        connect()
    } else {
        fmt.Println("Non-acceptable input. Please enter \"0\" or \"1\".")
    }

}


func connect() {
    conn, err := net.Dial("tcp", ":81")
    if err != nil {
        fmt.Printf("Error: Could not connect due to '%v'\n", err)
        os.Exit(1)
    }
    for {
        buffer := make([]byte, 1024)
        size, err := conn.Read(buffer)
        if err != nil {
            fmt.Printf("Error: Could not read from connection due to '%v'\n", err)
            os.Exit(1)
        }
        fmt.Printf("Read: %s\n", buffer[:size])
    }

    
}

func listen() {
    var conns []net.Conn
    var userInput int

    listener, err := net.Listen("tcp", ":81")
    if err != nil {
        fmt.Printf("Error: Could not listen due to '%v'\n", err)
        os.Exit(1)
    }

    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Printf("Error: Could not accept connection due to '%v'\n", err)
            os.Exit(1)
        }
        conns = append(conns, conn)

        fmt.Printf("New connection. Write to all connections? Yes[1], No[0]")
        fmt.Scan(&userInput)
        if userInput == 1 { 
            var data []byte 
            fmt.Printf("Insert message:\n")
            data, err := io.ReadAll(os.Stdin)
            if err != nil {
                fmt.Printf("Error: Could not read data to be sent to all connections due to '%v'\n", err)
                os.Exit(1)
            }
            writeToConnections(&conns, data) 
        } 
    }
}


func writeToConnections(conns *[]net.Conn, data []byte) {
    for _, conn := range *(conns) {
        go func(conn net.Conn, data []byte) {
            size, err := conn.Write(data)
            if err != nil {
                fmt.Printf("Error: Could not accept connection due to '%v'\n", err)
                os.Exit(1)
            }
            fmt.Printf("Amount of data written: %d\n", size)
        }(conn, data)
    }
}

I am new to Go, so it might not be the best solution. To sum up it, I save all connections in an array. At every new connection the listener gets asked if they wish to send a message to all connections. In case they choose to do so, they can type it on the terminal and send it after pressing CTRL-D twice to signal EOF. After this all instances of the program that chose to connect should see the message.

Reasons:
  • RegEx Blacklisted phrase (1.5): I am new
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Marina Santana