Added tcp-movie exercise

Need to practice sockets more, I have many ideas on what to do with them
This commit is contained in:
raul 2024-03-11 08:29:41 +01:00
parent 7693f81e0b
commit 290d1be8f4
2 changed files with 53 additions and 0 deletions

3
tcp-movie/go.mod Normal file
View File

@ -0,0 +1,3 @@
module tcp-movie
go 1.22.1

50
tcp-movie/main.go Normal file
View File

@ -0,0 +1,50 @@
package main
import (
"fmt"
"net"
"os"
//"time"
)
var LISTENING_PORT = 1337
func main() {
ln, err := net.Listen("tcp", ":1337")
catchErr(err)
fmt.Println("Listening on port 1337...")
for {
conn, err := ln.Accept()
catchErr(err)
go handleConn(conn)
}
}
func getIP(conn net.Conn) {
if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
fmt.Printf("Received connection from: %v\n", addr)
}
}
func handleConn(conn net.Conn) {
defer conn.Close()
getIP(conn)
//fmt.Printf("\rWelcome to my server!")
//time.Sleep(time.Second)
//fmt.Printf("\r")
//fmt.Printf("\rWhat, were you expecting something?")
conn.Write([]byte("\rWelcome to my server!"))
}
func catchErr(err error) (errHappened bool) {
errHappened = false
if err != nil {
errHappened = true
fmt.Println(err)
os.Exit(2)
}
return errHappened
}