Winsock程序设计初步之<三> 源程序实例(2)
//A simplest web client
//Written by Shen zhiliang for learning Winsock & HTTP
//zhiliang@sina.com
//1998.7.29
#include "winsock.h"
#include "stdio.h"
#define BUFLEN 4096
void SocketError(char * call)
{
fprintf(stderr," WinSock Error# function: %s, error code:%ld",call,WSAGetLastError());
}
main(int argc,char ** argv)
{
int iRes,iPort,iTmp;
SOCKET s,rs;
SOCKADDR_IN sin,rsin;
WSADATA wsad;
WORD wVersionReq;
char recvBuf[BUFLEN];
if(argc<4)
{
fprintf(stderr,"Usage: sockserver ip port message");
return -1;
}
if(inet_addr(argv[1])==INADDR_NONE)
{
fprintf(stderr,"Error ip gaving");
return -1;
}
iPort=0;
iPort=atoi(argv[2]);
sin.sin_addr.s_addr=inet_addr(argv[1]);
sin.sin_family=PF_INET;
sin.sin_port=htons(iPort);
if(iPort<=0)
{
fprintf(stderr,"must specify a number for port");
return -1;
}
wVersionReq=MAKEWORD(1,1);
iRes=WSAStartup(wVersionReq,&wsad);
if(iRes!=0)
{
SocketError("WSAStartup()");
return -1;
}
s=socket(PF_INET,SOCK_STREAM,0);
if(s==INVALID_SOCKET)
{
SocketError("socket()");
return -1;
}
iTmp=sizeof(sin);
fprintf(stderr,"WinSock Client Start......");
if(connect(s,(LPSOCKADDR)&sin,iTmp)==SOCKET_ERROR)
{
SocketError("connect()");
closesocket(s);
WSACleanup();
return -1;
}
strcpy(recvBuf,argv[3]);
strcat(recvBuf,"");
iRes=send(s,recvBuf,strlen(recvBuf),0);
if(iRes==SOCKET_ERROR)
{
SocketError("send()");
closesocket(s);
WSACleanup();
return -1;
}
printf("Sent Data:------------------%s------------------",recvBuf);
FILE * fp=fopen("send.dat","a+b");
if(fp==NULL)
return -1;
iRes=recv(s,recvBuf,BUFLEN,0);
while(iRes!=SOCKET_ERROR&&iRes!=0)
{
printf("Received Data:------------------%s------------------",recvBuf);
fwrite(recvBuf,sizeof(char),iRes,fp);
iRes=recv(s,recvBuf,BUFLEN,0);
}
fclose(fp);
closesocket(s);
WSACleanup();
return 0;
}