2 u012293946 u012293946 于 2014.05.06 15:33 提问

socket传输文件时遇到的问题!

先给出代码。
客户端:
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(4444);

HANDLE fp =CreateFile(L"E:\aTest.txt",GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

DWORD fileLen =GetFileSize(fp, &fileLen);
cout << "你选择的文件大小为:" << fileLen << endl;

connect(sockClient, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));

char * buffer = new char[fileLen];
DWORD bufferLen = 0;

ReadFile(fp, buffer, fileLen, &bufferLen, NULL);

bool isFirst = true;
int sendLen = 0;
int sentLen = 0;
char sendBuffer[200];
int leftLen = fileLen;

while (true)
{
if (isFirst)
{
sendLen = send(sockClient, "Test", 1, 0);
isFirst = false;
if (sendLen < 0)
{
cout << "第一帧发送失败,程序结束." << endl;
break;
}
Sleep(1000);
continue;
}

if ((leftLen <= 0) || (sentLen >= fileLen))
break;

if (leftLen >= 200)
{
memcpy(sendBuffer, buffer + sentLen, 200);
sendLen = send(sockClient, sendBuffer, 200, 0);
if (sendLen < 0)
{
cout << "帧发送失败,程序结束." << endl;
break;
}
}

else
{
memcpy(sendBuffer, buffer + sentLen, leftLen);
sendLen = send(sockClient, sendBuffer, leftLen, 0);
if (sendLen < 0)
{
cout << "帧发送失败,程序结束." << endl;
break;
}
Sleep(1000);
send(sockClient, "#", 1, 0);
}
sentLen += sendLen;
leftLen = fileLen - sentLen;
cout << "已经发送" << sentLen << endl;
}

if (sentLen == fileLen)

cout << "文件发送成功." << endl;
else
cout << "文件发送失败." << endl;

closesocket(sockClient);
WSACleanup();
delete[] buffer;
}
服务器端:
SOCKET socksrv = socket(AF_INET, SOCK_STREAM, 0);

SOCKADDR_IN addrsrv;
addrsrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrsrv.sin_family = AF_INET;
addrsrv.sin_port = htons(4444);

bind(socksrv, (sockaddr*)&addrsrv, sizeof(SOCKADDR));

listen(socksrv, 5);

SOCKADDR_IN addrclient;
int len = sizeof(SOCKADDR);

int recvLen = 0;
int recvedLen = 0;
DWORD writeLen;
int fileLen = 0;
char* buffer;
char recvBuffer[200];

while (1)
{
SOCKET sockconn = accept(socksrv, (SOCKADDR*)&addrclient, &len);

buffer = new char[1024 * 1024 * 10];
recvLen = recv(sockconn, recvBuffer, 200, 0);
if (recvBuffer[0] == 'test')
{
printf("开始接收文件\n");
memset(recvBuffer, 0, 200);
}
while (true)
{
recvLen = recv(sockconn, recvBuffer, 200, 0);
if ((recvLen == 1) && (recvBuffer[0] == '#'))
break;
memcpy(buffer + recvedLen, recvBuffer, recvLen);
recvedLen += recvLen;
printf("接收:%d\n", recvLen);
printf("已经接收%i字节数据\n", recvedLen);
}
HANDLE fp = CreateFile(L"C://Users\apple\Desktop", GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
WriteFile(fp, buffer, recvedLen, &writeLen, NULL);
printf("写入文件长度:%u\n", writeLen);

delete[] buffer;
WSACleanup();

}
}
代码有点乱,还有许多要改的地方,但是大体框架是这样。
运行的时候,客户端能够成功发送文件,服务器端也能正确显示接受的文件大小,然后写入文件却是0,然后就报错,不知道是为什么?

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!