0%

Go net包之TCP

net 包中关于 TCP 的简单应用

net 包介绍

Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.
Although the package provides access to low-level networking primitives, most clients will need only the basic interface provided by the Dial, Listen, and Accept functions and the associated Conn and Listener interfaces. The crypto/tls package uses the same interfaces and similar Dial and Listen functions.

The Dial function connects to a server:

conn, err := net.Dial("tcp", "golang.org:80")
if err != nil {
    // handle error
}
fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
status, err := bufio.NewReader(conn).ReadString('\n')
// ...

The Listen function creates servers:

ln, err := net.Listen("tcp", ":8080")
if err != nil {
    // handle error
}
for {
    conn, err := ln.Accept()
    if err != nil {
        // handle error
    }
    go handleConnection(conn)
}

TCP 示例

TCP 服务端

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
func main() {
tcpAddr, _ := net.ResolveTCPAddr("tcp", ":8888")
listener, _ := net.ListenTCP("tcp", tcpAddr)
for {
conn, err := listener.AcceptTCP()
if err != nil {
fmt.Println(err)
return
}
go handleConnection(conn)
}
}

func handleConnection(conn *net.TCPConn) {
for {
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
break
}
reply := string(buf[:n])
fmt.Println(conn.RemoteAddr().String() + ": " + reply)
reply = "收到了:" + reply
conn.Write([]byte(reply))
}
}

TCP 客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
func main() {
tcpAddr, _ := net.ResolveTCPAddr("tcp", ":8888")
conn, _ := net.DialTCP("tcp", nil, tcpAddr)
reader := bufio.NewReader(os.Stdin)
for {
bytes, _, _ := reader.ReadLine()
conn.Write(bytes)

readBuf := make([]byte, 1024)
readNum, _ := conn.Read(readBuf)
fmt.Println(string(readBuf[:readNum]))
}
}