-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
47 lines (40 loc) · 850 Bytes
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
import (
"flag"
"log"
"net"
"strconv"
)
func main() {
port := flag.Int("port", 8080, "Port to accept connections on.")
host := flag.String("host", "0.0.0.0", "Host or IP to bind to")
flag.Parse()
l, err := net.Listen("tcp", *host+":"+strconv.Itoa(*port))
if err != nil {
log.Panicln(err)
}
log.Println("Listening to connections at '"+*host+"' on port", strconv.Itoa(*port))
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
log.Panicln(err)
}
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn) {
log.Println("Accepted new connection.")
defer conn.Close()
defer log.Println("Closed connection.")
for {
buf := make([]byte, 1024)
size, err := conn.Read(buf)
if err != nil {
return
}
data := buf[:size]
log.Println("Received:", string(data))
conn.Write(data)
}
}