User Tools

Site Tools


,

Simple example of TCP server

server

tcpclient.go
package main
 
import (
    "net"
    "fmt"
    "bufio"
    "time"
    "os"
)
 
const (
    delim byte = 0x0A
)
 
func main() {
    fmt.Println("")
 
    listener, err:= net.Listen("tcp", ":8081")
    if err != nil {
        fmt.Println("#listen err:", err)
        os.Exit(1)
    }
    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("#accept err:", err)
            continue
        }
        remoteAddr := conn.RemoteAddr().String()
        fmt.Println("#accept", remoteAddr)
        go handler(conn)
    }
}
 
func handler(conn net.Conn) {
    defer conn.Close()
    start := time.Now()
    remoteAddr := conn.RemoteAddr().String()
 
    request, err := bufio.NewReader(conn).ReadBytes(delim)
    if err != nil {
        fmt.Println("#read err:", err)
        return
    }
    fmt.Println("#request", remoteAddr, string(request))
 
    response := []byte("hello")
    response = append(response, delim)
    conn.Write(response)
 
    elapsed := time.Since(start)
    fmt.Println("#close", remoteAddr, elapsed)
}
//EOF

client

tcpclient.go
package main
 
import (
    "net"
    "fmt"
    "bufio"
    "os"
    "time"
)
 
const (
    delim byte = 0x0A
)
 
func main() {
    conn, err := net.Dial("tcp", "127.0.0.1:8081")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    request := []byte("hello")
    request = append(request, delim)
 
    start := time.Now()
    conn.Write(request)
    response, _ := bufio.NewReader(conn).ReadBytes(delim)
    elapsed := time.Since(start)
 
    fmt.Println("#response:", string(response))
    fmt.Println("#elapsed:", elapsed)
}
//EOF

server out

$ go run serv.go 
#accept 127.0.0.1:44852
#request 127.0.0.1:44852 hello
#close 127.0.0.1:44852 71.531µs