编译环境:VC++6.0
/*
*File:client.cpp
*
*/
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#define DEFAULT_PORT 5150
#define DEFAULT_BUFFER 4096
#define DEFAULT_MESSAGE "LOGIN"
#define DEFAULT_COUNT 20
int iPort = DEFAULT_PORT;
char szServer[128];
char szMessage[1024];
DWORD dwCount = DEFAULT_COUNT;
BOOL bSendOnly = FALSE;
//Function:usage
//Description:
// Print usage information and exit
void usage()
{
printf("usage:client [-p:x] [-i:ip] [-n:x] [-o] /n/n");
printf(" -p:x Remote port to send to /n");
printf(" -i:str Server's address or host name /n");
printf(" -n:x Number of times to send message/n");
printf(" -o Send messages only;don't recevie/n");
printf("camel 2004-8-29");
ExitProcess(1);
}
// Function:
void ValidateArgs(int argc,char **argv)
{
int i;
for (i = 1; i < argc ;i++)
{
if ((argv[i][0]=='-') || (argv[1][0]=='/') )
{
switch (tolower(argv[i][1]))
{
case 'p':
iPort = atoi(&argv[i][3]);
break;
case 'i':
if(strlen(argv[i]) > 3)
strcpy(szServer,&argv[i][3]);
break;
case 'n':
if(strlen(argv[i])>3)
dwCount = atoi(&argv[i][3]);
case 'o':
bSendOnly = TRUE;
break;
default:
usage();
break;
}
}
}
}
int main(int argc,char ** argv)
{
WSADATA wsd;
SOCKET sClient;
char szBuffer[DEFAULT_BUFFER];
int ret,i;
struct sockaddr_in server;
struct hostent *host = NULL;
printf("======client====/n");
ValidateArgs(argc,argv);
if (WSAStartup(MAKEWORD(2,2),&wsd)!=0)
{
printf("Failed to load Winsock!/n");
return 1;
}
strcpy(szMessage,DEFAULT_MESSAGE);
//
//Create the socket,and attempt to connect to the server
//
sClient = socket(AF_INET,SOCK_STREAM,IPPROTO_IP);
if (sClient == SOCKET_ERROR)
{
printf("socket() failed: %d/n",WSAGetLastError());
return 1;
}
//Select the local interface,and bind to it
server.sin_family = AF_INET;
server.sin_port = htons(iPort);
server.sin_addr.s_addr = inet_addr(szServer);
//
//If the supplied server address wasn't in the form
//"aaa.bbb.ccc.ddd" It's a host name, so try to resolver it
//
if(server.sin_addr.s_addr == INADDR_NONE)
{
host = gethostbyname(szServer);
if(host == NULL)
printf("Unable to resolve server:%s/n",szServer);
return 1;
}
printf("debug: CopyMemory");
//CopyMemory(&server.sin_addr,host->h_addr_list[0],host->h_length);
printf("debug: CopyMemory over");
if(connect(sClient,(struct sockaddr *)&server,sizeof(server)) == SOCKET_ERROR)
{
printf("connect() failed:%d]n",WSAGetLastError());
return 1;
}
//
//Send and receive data
//
for(i = 0; i<dwCount;i++)
{
ret = send(sClient,szMessage,strlen(szMessage),0);
if (ret == 0 )
break;
else if(ret == SOCKET_ERROR)
{
printf("send() failed:%d/n",WSAGetLastError);
break;
}
printf("send %d bytes/n",ret);
if( !bSendOnly)
{
ret = recv(sClient,szBuffer,DEFAULT_BUFFER,0);
if(ret == 0)
break;
else if(ret == SOCKET_ERROR)
{
printf("recv() failed:%d/n",WSAGetLastError());
break;
}
szBuffer[ret] = '/0';
printf("RECV [%d bytes]:'%s'/n",ret,szBuffer);
}
}
closesocket(sClient);
WSACleanup();
return 0;
}