服务器端
package main
import (
"fmt"
"net"
"strings"
)
func HandleConnect( conn net.Conn) {
defer conn.Close()
addr:=conn.RemoteAddr()
fmt.Println(addr,"客户端成功连接")
buf:=make([]byte,4096)
for {
n,err:=conn.Read(buf)
if "exit\n" == string(buf[:n]) || "exit\r\n" == string(buf[:n]){
fmt.Println("客户端关闭连接")
return
}
if n ==0 {
fmt.Println("Client is close")
return
}
if err != nil {
fmt.Println("conn Read err",err)
return
}
fmt.Println("服务器读到客户端数据:",string(buf[:n]))
conn.Write([]byte(strings.ToUpper(string(buf[:n]))))
}
}
func main(){
listener,err:= net.Listen("tcp","127.0.0.1:9001")
if err != nil {
fmt.Println("net.listen is error")
return
}
defer listener.Close()
fmt.Println("服务器等待客户端连接...")
for {
conn,err:= listener.Accept()
if err != nil {
fmt.Println("accept is error")
return
}
go HandleConnect(conn)
}
}
客户端
package main
import (
"fmt"
"net"
"os"
)
func main(){
conn,err:=net.Dial("tcp","127.0.0.1:9001")
if err != nil {
fmt.Println("connect server is error")
return
}
defer conn.Close()
go func(){
str:=make([]byte,4096)
for {
n,err:=os.Stdin.Read(str)
if n ==0 {
fmt.Println("server is close")
return
}
if err != nil {
fmt.Println("os.Stdin is error")
continue
}
conn.Write(str[:n])
}
}()
//读取服务器
buf:=make([]byte,4096)
for {
n,err:=conn.Read(buf)
if n == 0 {
fmt.Println("服务端关闭连接了...")
return
}
if "exit\n" == string(buf[:n]) || "exit\r\n" == string(buf[:n]) {
fmt.Println("客户端关闭连接")
return
}
if err != nil {
fmt.Println("os.buf is error")
return
}
fmt.Println("客户端读到服务端数据:", string(buf[:n]))
}
}
标签:return,err,fmt,tcp,Println,buf,连接,conn
From: https://www.cnblogs.com/zh718594493/p/16932601.html