-
Notifications
You must be signed in to change notification settings - Fork 6
/
go-tcp-echo.go
47 lines (40 loc) · 864 Bytes
/
go-tcp-echo.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", 3333, "Port to accept connections on.")
host := flag.String("host", "127.0.0.1", "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("Read new data from connection", data)
conn.Write(data)
}
}