简体   繁体   English

如何在C中的套接字上读取超过256个字节

[英]how to read more than 256 bytes over a socket in C

I am facing the problem that my server is sending a string which is of size 600 bytes. 我面临的问题是我的服务器正在发送大小为600字节的字符串。 Now for reading from the server my client uses the statement 现在,为了从服务器读取,我的客户端使用了以下语句

   n=read(sockfd,rbuffer,255);

where rbuffer is my buffer. 其中rbuffer是我的缓冲区。

If i try to increase the size mentioned in the read statement (255) i'm getting a segmentation fault. 如果我尝试增加read语句(255)中提到的大小,则会遇到分段错误。

Now that I know that the client is receiving only the partial information sent by the server.How can I modify or change the way I read the information so that I can read all of the bytes? 现在我知道客户端仅接收服务器发送的部分信息,如何修改或更改读取信息的方式以便可以读取所有字节?

PS: the size of the string is so big since I am trying to send an XML string across. PS:字符串的大小太大,因为我正尝试发送XML字符串。

You need to also increase the size of rbuffer . 您还需要增加rbuffer的大小。 One way to do that could be: 一种方法是:

unsigned char rbuffer[4096];
n = read(socksfd, rbuffer, sizeof(rbuffer));

That way if you decide to change the size you only have to do it in one place. 这样,如果您决定更改大小,则只需在一个地方进行即可。

Well, when you look at the read() system call documentation, it says that the last argument is the size of your buffer. 好了,当您查看read()系统调用文档时,它说最后一个参数是缓冲区的大小。

In your case, you'll want to make sure that rbuffer is large enough! 对于您的情况,您需要确保rbuffer足够大!

I guess you have somewhere: 我猜你在某个地方:

unsigned char rbuffer[255];
n = read( sockfd, rbuffer, 255);

You'll want to do that: 您需要这样做:

unsigned char rbuffer[1024];
n = read( sockfd, rbuffer, 1024);

To be sure not to put an invalid value as the size, use sizeof( rbuffer ) if it is allocated on the stack (like above). 为了确保不要将无效值作为大小, 如果在堆栈上分配了大小,则使用sizeof( rbuffer ) (如上)。

If it is dynamically allocated, you'll have to use the size you used when allocating the buffer: 如果是动态分配的,则必须使用分配缓冲区时使用的大小:

int bufsize = 1024;
char *buffer = malloc(bufsize);
n = read( sockfd, buffer, bufsize);

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

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