ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Winsock程序设计初步之<三> 源程序实例(2) (转)

Winsock程序设计初步之<三> 源程序实例(2) (转)

原创 Linux操作系统 作者:amyz 时间:2007-10-02 15:50:05 0 删除 编辑
Winsock程序设计初步之<三> 源程序实例(2) (转)[@more@]

//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:%ldn",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 messagen");

return -1;

}

if(.NET_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=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......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/10752019/viewspace-974578/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
  • 博文量
    3984
  • 访问量
    7363952