socket发送和接收固定长度数据的函数

#include "stdafx.h"
#include "ATLComTime.h"
#include "Functions.h"
#include    
#pragma   comment(lib,   "rpcrt4.lib ") 


CRITICAL_SECTION _criticalLog;


extern string _ExePath;


//接收數據包
int SocketRecvFunc(SOCKET s, char *buf, int len, int timeout)
{
fd_set fdread;
int iRecvlen, iRead, iRecError;
int iResult=0;
LONG lRecvSize = len;
timeval time={timeout,0};//超时时长5秒 

while( s != INVALID_SOCKET )
{
FD_ZERO(&fdread);
FD_SET(s,&fdread);


iRead = select( 0, &fdread, NULL, NULL, &time );


if( iRead == 0 )//接收超时
break;


if( iRead == SOCKET_ERROR )
{
iResult = iRead;
break;
}


if( iRead > 0 )
{
if( FD_ISSET(s, &fdread) )
{
iRecvlen = recv( s, buf+(len-lRecvSize), lRecvSize, NULL );


if( iRecvlen == 0 )
{
iResult = iRecvlen;
break;
}


if( iRecvlen == SOCKET_ERROR )
{
iRecError = WSAGetLastError();


if( (iRecError == WSAENOTCONN)//(WSABASEERR+57)
|| (iRecError == WSAESHUTDOWN)//(WSABASEERR+58)
|| (iRecError == WSAENOTSOCK)
|| (iRecError == WSAENETDOWN)
|| (iRecError == WSAECONNABORTED)//(WSABASEERR+53)
|| (iRecError == WSAETIMEDOUT)//(WSABASEERR+60)
|| (iRecError == WSAECONNRESET) )//(WSABASEERR+54)
{
iResult = iRecvlen;
break;
}
}


lRecvSize -= iRecvlen;
iResult += iRecvlen;


//接收到完整数据包后再处理(因为每次recv的数据长度不一定等于发送包的长度)
if (lRecvSize <= 0)
break;
}
}
}


return iResult;
}


//发送数据包
int SocketSendFunc(SOCKET s, const char *buf, int len)
{
fd_set fdwrite;
int iSendlen;
int lSendSize=0;
int iResult=0;
int iWrite;
timeval timeout={2,0};//超时时长


do
{
FD_ZERO(&fdwrite);
FD_SET(s,&fdwrite);

iWrite = select(0, NULL, &fdwrite, NULL, &timeout);

if (iWrite == 0)
{
iResult = iWrite;
break;
}
if (iWrite == SOCKET_ERROR)
{
iResult = iWrite;
break;
}
if (iWrite > 0)
if (FD_ISSET(s,&fdwrite))
{
iSendlen = send(s, buf+lSendSize, len-lSendSize, NULL);
if (iSendlen == SOCKET_ERROR)
{
iResult = iSendlen;
break;
}
else
lSendSize += iSendlen;


iResult = lSendSize;
}
}while((lSendSize < len) && (s != INVALID_SOCKET));//判断是否发送完毕


return iResult;
}


int SocketSendFunc(SOCKET s, const char *buf, int len, bool* blockflag)
{
fd_set fdwrite;
int iSendlen;
int lSendSize=0;
int iResult=0;
int iWrite;
timeval timeout={2,0};//超时时长


do
{
FD_ZERO(&fdwrite);
FD_SET(s,&fdwrite);

iWrite = select(0, NULL, &fdwrite, NULL, &timeout);

if (iWrite == 0)
{
if (*blockflag)
continue;


iResult = iWrite;
break;
}


if (iWrite == SOCKET_ERROR)
{
iResult = iWrite;
break;
}
if (iWrite > 0)
if (FD_ISSET(s,&fdwrite))
{
iSendlen = send(s, buf+lSendSize, len-lSendSize, NULL);
if (iSendlen == SOCKET_ERROR)
{
iResult = iSendlen;
break;
}
else
lSendSize += iSendlen;


iResult = lSendSize;
}
}while((lSendSize < len) && (s != INVALID_SOCKET));//判断是否发送完毕


return iResult;
}


UINT ConnectToServer(char* szServer, WORD nPort)
{
SOCKET sSocket;
struct sockaddr_in serveraddr;
FD_SET mask;
u_long value=1;
TIMEVAL timeout;


sSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (sSocket == INVALID_SOCKET)
{
sSocket = 0;
}else
{
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(nPort);
serveraddr.sin_addr.s_addr = inet_addr(szServer);

ioctlsocket(sSocket,FIONBIO,&value);//设置为非阻塞
connect(sSocket,(struct sockaddr *)&serveraddr,sizeof(serveraddr));
timeout.tv_sec=2;
timeout.tv_usec=0;
FD_ZERO(&mask);
FD_SET(sSocket,&mask);


value=select(NULL,NULL,&mask,NULL,&timeout);
if(value && value!=SOCKET_ERROR)

//连接成功
value = 0;
ioctlsocket(sSocket,FIONBIO,&value);//设置为阻塞
}
else
{
shutdown(sSocket,SD_BOTH);
closesocket(sSocket);
sSocket = 0;
}
}


return sSocket;
}


void WriteLogFile(char* szLog)
{
COleDateTime t(COleDateTime::GetCurrentTime());
FILE *file=NULL;
errno_t err;
char szTxt[128]={};


LockCS lock( &_criticalLog );
sprintf_s( szTxt, sizeof(szTxt), "%d-%d-%d %d:%d:%d  ", t.GetYear(), t.GetMonth(), t.GetDay(), t.GetHour(), t.GetMinute(), t.GetSecond() );


if( 0 == (err  = fopen_s( &file, "MRVideoServer.log", "a+" )))
{
if( file != NULL )
{
fprintf_s( file, "%s", szTxt );
fflush(file);
fprintf_s( file, "%s", szLog );
fflush(file);
fprintf_s( file, "\r\n" );
fflush(file);


fclose(file);
}
}
}


void WriteLogFileEx(char* szLog,char* szPath)
{
COleDateTime t(COleDateTime::GetCurrentTime());
FILE *file=NULL;
errno_t err;
char szTxt[128]={};


LockCS lock( &_criticalLog );
sprintf_s( szTxt, sizeof(szTxt), "%d-%d-%d %d:%d:%d  ", t.GetYear(), t.GetMonth(), t.GetDay(), t.GetHour(), t.GetMinute(), t.GetSecond() );


if( 0 == (err  = fopen_s( &file, szPath, "a+" )))
{
if( file != NULL )
{
fprintf_s( file, "%s", szTxt );
fflush(file);
fprintf_s( file, "%s", szLog );
fflush(file);
fprintf_s( file, "\r\n" );
fflush(file);


fclose(file);
}
}
}


int MakeVideoID(short ConnectID,short SubID)
{
int iResult = 0;


if ((0 > ConnectID ) || (0 > SubID))
iResult = -1;
else
iResult = (ConnectID << 16) | (SubID);


return iResult;
}


void AnalysisID(int iID,short* pConnectID,short* pSubID)
{
if (0 > iID)
{
*pConnectID = -1;
*pSubID = -1;
}else
{
*pConnectID = (iID >> 16);
*pSubID = (short)iID;
}
}


void DwordIPToChar(DWORD dwIP,char* szIP)
{
char* szTempIP = NULL;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.S_un.S_addr = dwIP;
szTempIP = inet_ntoa(addr.sin_addr);
strcpy_s(szIP,128,szTempIP);
}


DWORD CharIPToDWORD(const char* szIP)
{
return inet_addr(szIP);
}


bool compare(const GUID &guidl, const GUID &guidr)
{
char *pszGuid_l = NULL;
char *pszGuid_r = NULL;
string guid_l = "";
string guid_r = "";


UuidToStringA(&guidl,(RPC_CSTR*)&pszGuid_l);
UuidToStringA(&guidr,(RPC_CSTR*)&pszGuid_r);
guid_l = pszGuid_l;
guid_r = pszGuid_r;


if(guid_l.compare(guid_r) < 0)
return true;
else
return false;
}


bool MyIsEqualGuid(const GUID &guid1, const GUID &guid2)
{
return ((guid1.Data1 == guid2.Data1) && (guid1.Data2 == guid2.Data2));
}


bool IsFileExists(const char* lpszFileName)   
{   
WIN32_FIND_DATAA wfd;   
bool bRet;   
HANDLE hFind;   
hFind = FindFirstFileA(lpszFileName,   &wfd);   
bRet  = (hFind != INVALID_HANDLE_VALUE);   
FindClose(hFind);   
return   bRet;   
}  

你可能感兴趣的:(C/C++)