[Go] TCP Server

A bunch of brief intro of writing TCP server from scratch code.

Write to connection

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
import (
"fmt"
"io"
"log"
"net"
)

func main() {
li, err := net.Listen("tcp", ":8080") // return Listener(Accept(), Close(), Addr()), Error
if err != nil {
log.Panic(err)
}
defer li.Close()

for { // Infinite loop
conn, err := li.Accept() // Conn: Connection: reader + writer
if err != nil {
log.Println(err)
}

io.WriteString(conn, "\nHello from TCP server\n")
fmt.Fprintln(conn, "How is your day")
fmt.Fprintf(conn, "%v", "Well, I hope!")

conn.Close()
}
}

Read from connection

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
func main() {
li, err := net.Listen("tcp", ":8080")
if err != nil {
log.Panic(err)
}
defer li.Close()

for { // Infinite loop
conn, err := li.Accept()
if err != nil {
log.Println(err)
}

go handle(conn)
}
}

func handle(conn net.Conn) {
scanner := bufio.NewScanner(conn)
for scanner.Scan() { // return boolean, stops when reach the end of line
ln := scanner.Text() // Scan() keeps listening to the conn's port,
fmt.Println(ln)
}

defer conn.Close()
}

Response and request

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
func handle(conn net.Conn) {
defer conn.Close()

// read request
request(conn)

// write resposne
respond(conn)
}

func request(conn net.Conn) { // PRINT request connection OUT
i := 0
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
ln := scanner.Text()
fmt.Println(ln)
if i == 0 {
// request line
m := strings.Fields(ln)[0]
fmt.Println("***METHOD", m)
}
if ln == "" {
break
}
i++
}
}

func respond(conn net.Conn) {
body := `<!DOCTYPE html><html lang="en"><body>hello</body></html>`
fmt.Fprint(conn, "HTTP/1.1 200 OK\r\n")
fmt.Fprint(conn, body)
}