Server端代码:
#include "stdafx.h"
#include <winsock2.h>
#include <cstdio>
#include <wincrypt.h>
#include <time.h>
#include <cstring>
#include <iostream>
#include <string.h>
#define PORT 2345
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "shlwapi.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "crypt32.lib")
using namespace std;
const int MAX1=1000;
typedef long long LL;
typedef unsigned long long ULL;
int recvn(SOCKET s, char * recvbuf, unsigned int fixedlen)
{
int iResult;
int cnt=fixedlen; //剩余多少字节尚未接收
while ( cnt > 0 )
{
iResult = recv(s, recvbuf, cnt, 0);
if ( iResult < 0 )
{
printf("error: %d\n", WSAGetLastError());
return -1;
}
if ( iResult == 0 )//对方关闭连接,返回已接收到的小于fixedlen的字节数
return fixedlen - cnt;
recvbuf +=iResult;
cnt -=iResult;
}
return fixedlen;
}
int recvvl(SOCKET s)
{
int iResult;
unsigned int reclen; //用于存储报文头部存储的长度信息
unsigned int recvbuflen=0;
char filename[100];
TCHAR name[100];
char tmp[1000],recvbuf[1000];
memset(tmp,0,sizeof(tmp));
int i=0;
memset(filename,0,sizeof(filename));
while(true)
{
iResult = recvn(s, tmp, sizeof( char ));
if(tmp[0]=='#') break;
filename[i++]=tmp[0];
if ( iResult !=sizeof (char ))//没有成功接收到一个整型数据
{
if ( iResult == -1 )
{
printf("get the filename error: %d\n", WSAGetLastError());
return -1;
}
else
{
printf("connect closed when get the filename\n");
return 0;
}
}
}
cout<<"fil