Added tcp-movie exercise
Need to practice sockets more, I have many ideas on what to do with them
This commit is contained in:
parent
7693f81e0b
commit
290d1be8f4
|
@ -0,0 +1,3 @@
|
|||
module tcp-movie
|
||||
|
||||
go 1.22.1
|
|
@ -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
|
||||
}
|
Loading…
Reference in New Issue