发布网友 发布时间:2022-04-22 08:45
共3个回答
热心网友 时间:2022-07-10 05:24
//取出数据,这里发现数据接收不完整。。。。
int nRecv = recv(cliSock, buf, sizeof(CStock)*(N+2), 0);
你没有判断到底返回了多少数据,而只是检查了《=0.你怎么知道数据是否接受完毕?
另外你还要确定,对方是否采取了优雅关闭。否则有可能丢失数据。
你可以参考一下MSDN的示例:
----------------------------------------------------------------
#include <winsock2.h>
#include <stdio.h>
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
int __cdecl main() {
//----------------------
// Declare and initialize variables.
WSADATA wsaData;
int iResult;
SOCKET ConnectSocket;
struct sockaddr_in clientService;
char *sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
//----------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
//----------------------
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError() );
WSACleanup();
return 1;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
clientService.sin_port = htons( 27015 );
//----------------------
// Connect to server.
iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
if ( iResult == SOCKET_ERROR) {
closesocket (ConnectSocket);
printf("Unable to connect to server: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
} while( iResult > 0 );
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
热心网友 时间:2022-07-10 05:25
您的rp问题吧,我看没什么问题,愚见而已。
热心网友 时间:2022-07-10 05:25
A机 <-B机:接收数据完整!!!
是指AB的C/S身份互换一下,数据就完整吗?
换身份可以的话,难道是B机的防火墙之类、协议内部缓冲区大小等的设置有不同?你把
int nRecv = recv(cliSock, buf, sizeof(CStock)*(N+2), 0);
if(nRecv <=0)
{
}
换成循环检测nRecv大小,直到为0,试一下?说不定RP会变好的呵呵。
int nRecv = 0;
int pos=0;
while (1)
{
nRecv=recv(cliSock, buf+pos, sizeof(CStock)*(N+2)-pos, 0));
if(nRecv <=0)
{
break;
}
else
{
pos+=nRecv
}
}