tcp client端代碼tcp_client.go如下:
package main
import (
"fmt"
"net"
"os"
)
func main() {
conn, err := net.Dial("tcp", ":9000")
if err != nil {
fmt.Println("net.Dial err: ", err)
return
}
defer conn.Close()
go func() {
str := make([]byte, 1024)
for {
n, err := os.Stdin.Read(str)
if err != nil {
fmt.Println("os.Stdin.Read err:", err)
return
}
_, err = conn.Write(str[:n])
if err != nil {
fmt.Println("conn.Write err:", err)
return
}
}
}()
buf := make([]byte, 4096)
for {
n, err := conn.Read(buf)
if err != nil {
fmt.Println("conn.Write err:", err)
return
}
fmt.Println("client read data:", string(buf[:n]))
}
}
go build tcp_client.go
tcp server端代碼tcp_server.go如下:
package main
import (
"fmt"
"io"
"net"
"strings"
)
func handler(conn net.Conn) {
defer conn.Close()
addr := conn.RemoteAddr().String()
fmt.Println(addr, "connect success")
buf := make([]byte, 4096)
for {
n, err := conn.Read(buf)
if err != nil {
if err == io.EOF {
fmt.Println("client close")
return
}
fmt.Println("cnn.Read err: ", err)
return
}
fmt.Println("server receive:", string(buf[:n]))
if _, err := conn.Write([]byte(strings.ToUpper(string(buf[:n])))); err != nil {
fmt.Println("conn.Write err:", err)
}
}
}
func main() {
listener, err := net.Listen("tcp", ":9000")
if err != nil {
fmt.Println("net.Listen err: ", err)
return
}
defer listener.Close()
fmt.Println("waiting for client connect...")
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("listener.Accept err:", err)
return
}
go handler(conn)
}
}
go build tcp_server.go