Winsock程式設計初步之<三> 源程式例項(2) (轉)

gugu99發表於2008-04-04
Winsock程式設計初步之 源程式例項(2) (轉)[@more@]

//A simplest 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:%ldn",call,WSAGetLastError());

}

main(int argc,char ** argv)

{

int iRes,iPort,iTmp;

SOCKET s,rs;

SOCKADDR_IN sin,rsin;

WSADATA wsad;

wVersionReq;

char recvBuf[BUFLEN];

if(argc<4)

{

fprintf(stderr,"Usage: sockserver port messagen");

return -1;

}

if(_addr(argv[1])==INADDR_NONE)

{

fprintf(stderr,"Error ip gavingn");

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 portn");

return -1;

}

wVersionReq=MAKEWORD(1,1);

iRes=Wtartup(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......n");

if(connect(s,(LPSOCKADDR)&sin,iTmp)==SOCKET_ERROR)

{

SocketError("connect()");

closesocket(s);

WSACleanup();

return -1;

}

strcpy(recvBuf,argv[3]);

strcat(recvBuf,"rnrn");

iRes=send(s,recvBuf,strlen(recvBuf),0);

if(iRes==SOCKET_ERROR)

{

SocketError("send()");

closesocket(s);

WSACleanup();

return -1;

}

printf("Sent Data:n------------------n%sn------------------n",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:n------------------n%sn------------------n",recvBuf);

fwrite(recvBuf,sizeof(char),iRes,fp);

iRes=recv(s,recvBuf,BUFLEN,0);

}

fclose(fp);

closesocket(s);

WSACleanup();

return 0;

}


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10748419/viewspace-1001893/,如需轉載,請註明出處,否則將追究法律責任。

相關文章