描述:客户端可以接受服务端信息 & 写数据导服务端 服务端也一样
服务端代码

package main

import (
"bufio"
"fmt"
"io"
"net"
"os"
"strings"
)
func process(conn net.Conn){
defer conn.Close()
var buf[1024]byte
reader:=bufio.NewReader(conn)
for {
n,err:=reader.Read(buf[:])
if err == io.EOF {
break
}
if err != nil {
return
}
recvStr:= string(buf[:n])
fmt.Printf("收到客户端数据:%v\n",recvStr)
}
}

//想客户端写写入数据
func write(conn net.Conn){
defer conn.Close()
reader:=bufio.NewReader(os.Stdin)
for {
text,_:=reader.ReadString('\n')
text = strings.TrimSpace(text)
conn.Write([]byte(text))
}
}
func main(){
listener,err:=net.Listen("tcp","0.0.0.0:8890")
if err != nil {
fmt.Println("start server is erros")
return
}
fmt.Println("服务端启动成功...")
fmt.Println("等待客户端的连接...")
for {
conn,_:= listener.Accept()
go process(conn)
go write(conn)
}
defer listener.Close()
}

客户端代码

package main

import (
"bufio"
"fmt"
"io"
"net"
"os"
"strings"
)
func read(conn net.Conn){
defer conn.Close()
var buf[1024]byte
reader:=bufio.NewReader(conn)
for {
n,err:=reader.Read(buf[:])
if err == io.EOF {
break
}
if err != nil {
return
}
recvStr:= string(buf[:n])
fmt.Printf("收到服务端数据为:%v\n",recvStr)
}
}

func main(){
conn,err:= net.Dial("tcp","127.0.0.1:8890")
if err != nil {
fmt.Println("is erro")
}
reader:= bufio.NewReader(os.Stdin)
fmt.Printf("%v,\n","请写入内容")
for {
text,_:=reader.ReadString('\n')
text = strings.TrimSpace(text)
if text == "exit" {
break
}
conn.Write([]byte(text))

go read(conn)
}
conn.Close()
}