功能:客户端持续写入数据,直到输入exit退出,服务端读取数据并打印
注意:server和client目录在同一层级
服务端
server/main文章来源:https://www.toymoban.com/news/detail-827857.html
package main
import (
"fmt"
"net"
)
func main() {
listen, err := net.Listen("tcp", "0.0.0.0:8080")
if err != nil {
fmt.Printf("err: %v\n", err)
return
}
fmt.Println("server is listening")
defer listen.Close()
for {
conn, err2 := listen.Accept()
if err2 != nil {
fmt.Printf("err2: %v\n", err2)
return
}
fmt.Printf("server: %v\n", conn.LocalAddr())
go readData(conn)
}
}
func readData(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 1024)
for {
n, err := conn.Read(buf)
if err != nil {
fmt.Printf("err: %v\n", err)
return
}
fmt.Println("读取了", n, "字节数据")
fmt.Println("buf:", string(buf[:n]))
}
}
客户端
client/main
go开启协程,数据写入结束向管道输入信号,主线程获取信号,退出。否则主线程运行结束会直接退出文章来源地址https://www.toymoban.com/news/detail-827857.html
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
var exitchan chan bool
func main() {
fmt.Println("client is wating to connect")
conn, err := net.Dial("tcp", "192.168.0.1:8080")
if err != nil {
fmt.Printf("err: %v\n", err)
return
}
go writeData(conn)
if <-exitchan {
fmt.Print("client exit")
}
}
func writeData(conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(os.Stdin)
len := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
line = strings.Trim(line, "\r\n")
len, err = conn.Write([]byte(line))
if err != nil {
return
}
if line == "exit" {
break
}
fmt.Println("写入", len, "字节数据")
}
fmt.Println("client:", conn.RemoteAddr())
exitchan <- true
}
到了这里,关于go内置库函数实现client与server数据的发送接收的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!