简体   繁体   English

C Unix套接字编程,确保读/写字节数?

[英]C Unix socket programming, ensuring read/write byte counts?

I'm writing client and server programs and I'm looking for a way to ensure all bytes are read and all bytes are sent when using read() or write() to/from the sockets opened by the client/server. 我正在编写客户端和服务器程序,正在寻找一种方法,以确保在从客户端/服务器打开的套接字使用read()或write()时读取所有字节并发送所有字节。

I'm assuming I'll have to use a loop to check the number of bytes returned from the read or write functions. 我假设必须使用循环来检查从读取或写入函数返回的字节数。

Something like this probably: 大概是这样的:

#define BUFFER 20
char buffer[BUFFER];

while (I haven't read all bytes from the buffer){
       int bytesRead = read(theSocket, myWord, BUFFER);
 }

And how would I ensure that all the bytes I am trying to transmit using write() have been transmitted? 以及如何确保我尝试使用write()传输的所有字节均已传输?

Thanks for any help! 谢谢你的帮助!

Yes, exactly like that. 是的,完全一样。 Typical read logic goes like this: 典型的读取逻辑如下所示:

1) Call read . 1)调用read

2) Did we get EOF or error? 2)我们收到EOF还是错误? If so, return. 如果是这样,请返回。

3) Did we receive all the bytes? 3)我们收到了所有字节吗? If so, return. 如果是这样,请返回。

4) Go to step 1. 4)转到步骤1。

Note that when you call read , you'll need to pass it a pointer to the buffer after the data that was already read, and you'll need to try to read an appropriate amount of bytes that won't overflow the buffer. 请注意,当您调用read ,您需要在已读取的数据之后向其传递一个指向缓冲区的指针,并且您将需要尝试读取不会溢出缓冲区的适当数量的字节。 Also, how you tell if you received all the bytes depends on the protocol. 另外,如何确定是否收到所有字节取决于协议。

To write: 来写:

1) Call write , passing it a pointer to the first unwritten byte and the number of unwritten bytes. 1)调用write ,向它传递一个指向第一个未写字节和未写字节数的指针。

2) Did we get zero or error? 2)我们得到零或错误吗? If so, return. 如果是这样,请返回。

3) Did we write all the bytes? 3)我们写完所有字节了吗? If so, return. 如果是这样,请返回。

4) Go to step 1. 4)转到步骤1。

Note that you have to adjust appropriately for blocking or non-blocking sockets. 请注意,必须针对阻塞或非阻塞套接字进行适当调整。 For example, for non-blocking sockets, you have to handle EWOULDBLOCK . 例如,对于非阻塞套接字,您必须处理EWOULDBLOCK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM