在TCP客户端服务器中循环读写数据时的并发问题 [英] Concurrency issues while reading and writing data in loop in TCP client server
问题描述
我试图创建一个客户端服务器模型来学习一些知识,而我只是尝试以循环的方式从客户端向服务器发送(写入)数据,但是效果不佳.我认为存在一些并发性问题,客户端向服务器和服务器的写入速度比一次性读取多个语句要快.我如何保持这种并发性,以便服务器一次只能读取一个由客户端编写的语句.这是用来更好地说明问题的代码.
I was trying to create a client server model to learn some stuff and I just tried sending(writing) data from client to server in a loop and it just don't worked well. I think that there are some concurrency issues and the client writes faster to server and the server than read multiple statements in one go. How can I maintain this concurrency so that only one statement written by the client at a time is read by the server. Here is the code to illustrate the problem in a better.
这是服务器handleConnection函数
Here is the server handleConnection Function
func main() {
conn, err := net.Listen("tcp", ":8080")
if err != nil {
log.Println("Error:", err)
}
for {
ln, err := conn.Accept()
if err != nil {
log.Println("Error:", err)
continue
}
go handleConnection(ln)
}
}
func handleConnection(conn net.Conn) {
buffer := make([]byte, 4096)
for i := 0; i < 10; i++ {
n, err := conn.Read(buffer)
if err != nil {
fmt.Println(err, i)
}
fmt.Printf("%s\n", buffer[:n])
}
fmt.Println("Done")
conn.Close()
}
这里是客户端将数据循环写入服务器.
Here is the client writing data to server in loop.
func main() {
conn, err := net.Dial("tcp", ":8080")
if err != nil {
log.Println("Error:", err)
os.Exit(1)
}
for i := 0; i < 10; i++ {
_, err = conn.Write([]byte("Rehan"))
if err != nil {
fmt.Println(err, i)
}
}
fmt.Println("Done")
conn.Close()
}
这是服务器的输出. ] 1
This is the output by the server. ]1
推荐答案
这不是并发问题.这是一个网络问题.
It isn't a concurrency issue. It's a networking issue.
TCP是流协议,因此,来自套接字的单个read()
并不对应于来自另一端的单个write()
.
TCP is a stream protocol, as such, a single read()
from a socket doesn't correspond to a single write()
from the other side.
相反,无论读取是通过单次调用write()
还是发送一百个来发送的,读操作都会返回读取时TCP缓冲区中的内容.
Instead, reads return whatever is in the TCP buffer at the time of read, regardless whether it was sent by a single call to write()
or a hundred.
如果要将套接字中的数据作为单独的消息读取,则需要一种使用定界符,计数字节或其他方法将它们分离的方法.
If you want to read the data from the socket as separate messages, you need a way of separating them by using a delimiter, counting bytes, or some other method.
这篇关于在TCP客户端服务器中循环读写数据时的并发问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!