golang-exercises/sockets/main.go

47 lines
807 B
Go
Raw Normal View History

2024-03-09 19:35:26 +01:00
package main
import (
"bufio"
"fmt"
"net"
"os"
2024-03-09 19:35:26 +01:00
"strings"
)
2024-03-10 09:21:02 +01:00
var LISTENING_PORT string = ":1302"
2024-03-09 19:35:26 +01:00
func main() {
2024-03-10 09:21:02 +01:00
if len(os.Args) != 1 {
LISTENING_PORT = ":" + os.Args[1]
}
ln, err := net.Listen("tcp", LISTENING_PORT)
2024-03-09 19:35:26 +01:00
catchErr(err)
2024-03-10 09:21:02 +01:00
fmt.Printf("Listening on port %v...\n", strings.TrimLeft(LISTENING_PORT, ":"))
2024-03-09 19:35:26 +01:00
for {
conn, err := ln.Accept()
2024-03-09 19:35:26 +01:00
catchErr(err)
go handleConn(conn)
2024-03-09 19:35:26 +01:00
}
}
func handleConn(conn net.Conn) {
defer conn.Close()
message, err := bufio.NewReader(conn).ReadString('\n')
catchErr(err)
fmt.Printf("Message received: %v", string(message))
newMsg := strings.ToUpper(message)
2024-03-10 09:21:02 +01:00
conn.Write([]byte(newMsg))
}
2024-03-09 19:35:26 +01:00
func catchErr(err error) (errHappened bool) {
errHappened = false
if err != nil {
errHappened = true
fmt.Println(err)
os.Exit(2)
2024-03-09 19:35:26 +01:00
}
return errHappened
}