TCP Server and Client
Has been a while haven't write any blog, I am just trying to pick it up a bit. Recently, played around TCP a bit, even simpler than WebSocket(which I tried before) just write up a note the simple playground.
Before share the play code here are some details about the difference between TCP and WebSocket (opens new window), it is good to know before hand.
# TCP Server
Simple tcp server app,
server.go
:
/*
A very simple TCP server written in Go.
*/
package main
import (
"fmt"
"net"
"strconv"
)
const (
addr = ""
port = 8000
)
func main() {
src := addr + ":" + strconv.Itoa(port)
listener, err := net.Listen("tcp", src)
if err != nil {
fmt.Println(err.Error())
}
defer listener.Close()
fmt.Printf("TCP server start and listening on %s.\n", src)
for {
conn, err := listener.Accept()
if err != nil {
fmt.Printf("Some connection error: %s\n", err)
}
fmt.Println("accpet new connection!")
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
remoteAddr := conn.RemoteAddr().String()
fmt.Println("Client connected from: " + remoteAddr)
// Make a buffer to hold incoming data.
buf := make([]byte, 1024)
for {
// Read the incoming connection into the buffer.
reqLen, err := conn.Read(buf)
if err != nil {
if err.Error() == "EOF" {
fmt.Println("Disconned from ", remoteAddr)
break
} else {
fmt.Println("Error reading:", err.Error())
break
}
}
// Send a response back to person contacting us.
conn.Write([]byte(fmt.Sprintf("message received: %v \n", string(buf))))
fmt.Printf("len: %d, recv: %s\n", reqLen, string(buf[:reqLen]))
}
// Close the connection when you're done with it.
conn.Close()
}
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
just hit go run server.go
to get it started, then you can simply communicate with it using:
$ nc localhost 8000
hello world!
message received: hello world!
2
3
That simple!
# TCP Client
a client code, it s going to loop against the server, client.go
:
package main
import (
"bufio"
"fmt"
"log"
"net"
"time"
)
func main() {
// connect to this socket
conn, err := net.Dial("tcp", "127.0.0.1:8000")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
go func() {
i := 0
for {
time.Sleep(1 * time.Second)
conn.Write([]byte(fmt.Sprintf("msg index %v", i)))
i++
}
}()
// send to socket
// listen for reply
reader := bufio.NewReader(conn)
for i := 0; i < 100; i++ {
message, err := reader.ReadBytes('\n')
fmt.Println("process", i, string(message), "error", err)
}
}
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
Hit go run client.go
to get it executed!
That's all, simple XD