1

I am brand new to using sockets in the winapi, but I have this code and I am trying to print all data coming from a socket, but when I try printing it it comes out as a jumbled mix of symbols what am I doing wrong. I have looked around for examples on how to do this but none of the examples show how to print the data after it is collected from the buffer.

do 
{
#define DEFAULT_BUFLEN 512
int recvbuflen = DEFAULT_BUFLEN;
char recvbuf[DEFAULT_BUFLEN];
recv(ConnectSocket, recvbuf, recvbuflen, 0);
printf("%.*s", recvbuflen, recvbuf);
} 
while (iResult > 0);

ok guys i have changed my code to this

do 
{
#define DEFAULT_BUFLEN 1000000
int recvbuflen = DEFAULT_BUFLEN;
char recvbuf[DEFAULT_BUFLEN];
ssize_t len = recv(ConnectSocket, recvbuf, recvbuflen, 0);
recv(ConnectSocket, recvbuf, recvbuflen, 0);
printf("%.*s", recvbuflen, recvbuf);
} 
while (iResult > 0);

but now it doesnt seem to print all information from socket just first part

4

2 回答 2

2

正如 Valeri 和其他人所说,您不应忽略recv. 但是,默认情况下,所有套接字都是阻塞的,我没有看到您使用的是非阻塞套接字。所以除非连接被切断,否则recv会等到缓冲区满后再返回。我认为这不会导致您的问题。

如果您通过网络发送随机数据,那么您得到的结果正是人们所期望的。任何大于 127 的字符值称为扩展 ASCII可能看起来是一个奇怪的符号。低于 32 的字符值(也称为控制字符)可能会导致发出蜂鸣声或字符擦除。

于 2013-04-21T14:16:46.920 回答
1

您忽略了收到的内容的长度:

ssize_t len = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (len > 0)
{
    printf("%.*s", (int)len, recvbuffer);
}
else
{
    break; // error or EOF
}
于 2013-04-21T13:43:19.757 回答