Add tiny server to query-cpu exercise
This commit is contained in:
parent
18bd5f98a3
commit
4ba20dfc76
|
@ -14,4 +14,5 @@ func main() {
|
|||
}
|
||||
|
||||
fmt.Println(cpuCores)
|
||||
server()
|
||||
}
|
||||
|
|
|
@ -0,0 +1,50 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
)
|
||||
|
||||
func server() {
|
||||
fmt.Println()
|
||||
ln, err := net.Listen("tcp", ":8080")
|
||||
catchErr(err)
|
||||
fmt.Println("Listening...")
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
catchErr(err)
|
||||
go handleConn(conn)
|
||||
}
|
||||
}
|
||||
|
||||
func handleConn(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
message, err := bufio.NewReader(conn).ReadString('\n')
|
||||
catchErr(err)
|
||||
conn_IP := getIP(conn)
|
||||
final_message := fmt.Sprintf("Received connection from %v with message: %v", conn_IP, message)
|
||||
reply_message := fmt.Sprintf("Your message was sent successfully\n")
|
||||
conn.Write([]byte(reply_message))
|
||||
fmt.Println(final_message)
|
||||
|
||||
}
|
||||
|
||||
func getIP(conn net.Conn) (IP string) {
|
||||
if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
|
||||
IP = fmt.Sprintf("%v", addr)
|
||||
}
|
||||
return IP
|
||||
}
|
||||
|
||||
func catchErr(err error) (errHappened bool) {
|
||||
errHappened = false
|
||||
if err != nil {
|
||||
errHappened = true
|
||||
log.Fatalf("Error: %v\n", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
return errHappened
|
||||
}
|
Loading…
Reference in New Issue