服务端程序:
package main
import (
"net"
"fmt"
"strings"
)
func handle(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 2048)
for {
n, err := conn.Read(buf)
if err != nil {
fmt.Println("read err = ", err)
return
}
content := strings.TrimSpace(string(buf[:n]))
fmt.Println("receive =", content)
if content == "exit" {
return
}
conn.Write([]byte(strings.ToUpper(content)))
}
}
func main() {
ss, err := net.Listen("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("listen err = ", err)
return
}
fmt.Println("listening at 127.0.0.1:8000")
for {
conn, err := ss.Accept()
if err != nil {
fmt.Println("connect err = ", err)
return
}
go handle(conn)
}
}
客户端程序:
package main
import (
"net"
"fmt"
"os"
)
func ScanLine() string {
var c byte
var err error
var b []byte
for ; err == nil; {
_, err = fmt.Scanf("%c", &c)
if c != '\n' {
b = append(b, c)
} else {
break;
}
}
return string(b)
}
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("connect err = ", err)
return
}
go func(conn net.Conn) {
buf := make([]byte, 2048)
for {
n, err := conn.Read(buf)
if err != nil {
fmt.Println("read err = ", err)
return
}
fmt.Println(string(buf[:n]))
}
}(conn)
for {
input := ScanLine()
conn.Write([]byte(input))
if input == "exit" {
os.Exit(0)
}
}
}
注意事项:
1. 从键盘输入一行需要特别处理,否则可能出现一行输入数据被分为几段分别发送的情况
2. 注意客户端需新建协程处理从服务端接收的数据,主程处理键盘输入