上次写INTERNET编程的时候,忘记了说如何设置SOCKET选项.今天特地补回来.
我们就试着设置SOCKET接收数据的超时值.
好,那来看代码吧:
#include <stdio.h>
#include "winsock2.h"
void main()
{
/*-------------------------------------------*/
初始化套接字库
/*-------------------------------------------*/
WORD wVersionRequested; //版本号
WSADATA wsaData;
int ret;
wVersionRequested = MAKEWORD( 2, 2 ); //2.2版本的套接字
ret = WSAStartup( wVersionRequested, &wsaData );
if ( ret != 0 )
{
printf("加载套接字库失败!/n");
return ;
}
if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 )
{
printf("加载套接字库失败!/n");
WSACleanup();
return ;
}
/*-------------------------------------------*/
创建客户端
/*-------------------------------------------*/
hostent * pHost = NULL; //指向服务器主机的指针
SOCKET socket_client;
SOCKADDR_IN server; //服务器地址信息
pHost = gethostbyname( "127.0.0.1" );
if ( !pHost )
{
printf("无法解析服务器地址!错误原因:%d/n", WSAGetLastError() );
WSACleanup();
return ;
}
server.sin_addr.S_un.S_addr = *((DWORD*)pHost->h_addr_list[0]);
server.sin_family = AF_INET;
server.sin_port = htons(4443);
memset( server.sin_zero, 0, sizeof(server.sin_zero) );
socket_client = socket( AF_INET, SOCK_STREAM, 0 ); //创建套接字(socket)
if ( socket_client == INVALID_SOCKET )
{
printf("创建套接字失败!错误原因:%d/n", WSAGetLastError() );
WSACleanup();
return ;
}
if( SOCKET_ERROR == connect( socket_client , (SOCKADDR*)&server ,sizeof(SOCKADDR) ) )
{
printf( "连接服务器失败!错误原因:%d/n", WSAGetLastError() );
closesocket( socket_client );
WSACleanup();
return ;
}
//MS SOCKET 2以上版本才支持
int TimeOut = 3000;
if ( setsockopt( socket_client, SOL_SOCKET, SO_RCVTIMEO, (char*)&TimeOut, sizeof(TimeOut) ) != SOCKET_ERROR )
{
printf( "Set SO_RCVTIMEO: ON/n" );
}
/*if ( setsockopt( socket_client, SOL_SOCKET, SO_SNDTIMEO, (char*)&TimeOut, sizeof(TimeOut) ) != SOCKET_ERROR )
{
printf( "Set SO_SNDTIMEO: ON/n" );
}*/
do
{
char buffer[1024] = {0};
if( SOCKET_ERROR == recv( socket_client, buffer, 1023, 0 ) )
{
printf( "Error Occurs In recv : %d/n",WSAGetLastError() );
closesocket( socket_client );
return ;
}
printf( "recv : %s/n", buffer );
if ( strcmp(strupr(buffer),"QUIT") == 0 )
{
break;
}
printf( "Send:" );
scanf( "%s", buffer );
if( SOCKET_ERROR == send( socket_client, buffer, strlen(buffer) + 1, 0 ) )
{
printf( "发送数据失败!错误原因 : %d/n",WSAGetLastError() );
closesocket( socket_client );
WSACleanup();
return ;
}
if ( strcmp(strupr(buffer),"QUIT") == 0 )
{
break;
}
} while( TRUE );
printf("断开与服务器的连接!/n");
closesocket( socket_client );
WSACleanup();
}