今天遇到了一个SOCKET初始化的问题,运行平台在linux中,在windows中调试,就出现了socket一直返回-1的错误。
经网上查找后得以解决,解决办法是增加了两段代码,在windows中要使用socket,需要先注册。
以下为示例代码
//初始化TCP
Result TcpClient_Init(int localPort)
{
//add by guoyong Use to windows
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
DEBUG_KEYI(("\n\n-----TCP WSAStartup failed------\n\n"));
return S_FALSE;
}
//add end
localPort = localPort;
TcpClient_SocketId = socket(AF_INET,SOCK_STREAM,0);
if (TcpClient_SocketId == -1)
{
DEBUG_KEYI(("\n\n-----TCP Init failed:[%ld]------\n\n",WSAGetLastError())); //windows:WSAGetLastError() linux:errno
return S_FALSE;
}
DEBUG_KEYI(("\n\n-----TCP Init OK------\n\n"));
return S_OK;
}
//关闭TCP
void TcpClient_Close()
{
int ret = 0;
//add by guoyong Use to windows
WSADATA wsaData;
if ( LOBYTE( wsaData.wVersion ) != 1 || HIBYTE( wsaData.wVersion ) != 1 )
{
WSACleanup( );
return;
}
//add end
ret = close(TcpClient_SocketId);
if (ret == -1)
{
DEBUG_KEYI(("\n\n----------close socket handle failed!-------\n"));
}
TcpClient_SocketId = 0;
}
DEBUG_KEYI(("\n\n-----TCP WSAStartup failed------\n\n"));