欢迎来到天天文库
浏览记录
ID:46557756
大小:80.50 KB
页数:10页
时间:2019-11-25
《网络基础--代码》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、WINDOWSSOCKET编程例子;服务器程序/*****WINDOWSSOCKET编程例子;服务器程序*****/#includel,windows.hH#include#include#defineSERVER_PORT8888/*服务端口*/#defineMAX_MSG_SIZE1024/*缓冲区的大小*/#defineBACKLOG5厂等待服务的最大数*/intServer_Proc(intsockfd)厂服务过癌;服务器接受一条消息,然后发送一条消息*/intn;/*接受到的或发送的
2、数据的字节数*/charmsg[MAX_MSG_SIZE];/*缓冲区n=recv(sockfd,msgzMAX_MSG_SIZE/0);msg[n]=0;printf(吆s“msg);/*在屏幕上打印出来*/strcpy(msg,"hi,lamserver!");n=send(sockfd/msg/sizeof(msg),0);close(sockfd);return1;main(){intser_sockfd,/*服务器SOCKET*/cli_sockfd;/*客户端SOCKET*/interrno;intaddrlen;
3、void*optval;socklen_toptlen;structsockaddrjnser_addr,/*服务器的地址*/cli_addr;/*客户端的地址*/ser_sockfd=socket(AF_INET,SOCK_STREAM,0);/*创建连接的SOCKET*/if(ser_sockfd<0){/*创建失败*/errno=GetLastError();fprintffstderr/'sockerError:%s舄streiror(errno));exit(l);}/*初始化服务器地址*/addrlen=sizeo
4、f(structsockaddr_in);bzero(&ser_addr»addrlen);ser_addr.sin_family=AF_INET;ser_addr.sin_addr.s_addr=htonl(INADDR_ANY);ser_addr.sin_port=htons(SERVER_PORT);if(bind(ser_sockfd4structsockaddr*)&ser_addGsizeof(structsockaddr_in))<0){严棒定失败*/errno=GetLastError();fprintf(stde
5、rr/'BindErTor:%s",strerror(errno));exit(l);}if(listen(ser_sockfd/BACKLOG)<0)/*侦听客户端请求*/{errno=GetLastError();fprintf(stderr/'ListenError:%s",strerror(errno));close(ser_sockfd);exit(l);}while(l){厂等待接收客户连接请求*/cli_sockfd=accept(ser_sockfdz(structsockaddr*)&cli_addr,&
6、addrlen);if(cli_sockfd<=0){errno=GetLastError();fprintf(stderr/fAcceptError:%sll/strerror(errno));}{厂开始服务=7Server_Proc(cli_sockfd);}——}close(ser_sockfd);WINDOWSSOCKET编程例子;客户机程序*******WINDOWSSOCKET编程例子;客户机程序**********/#include#include#include7、tdio.h>#defineSERVER_PORT8888/*服务端口*/#defineMAX_MSG_SIZE1024/*缓冲区的大小*/intGetServerAddr(char*addrname){printff^Pleaseinputserveraddr:/z);scanf("%s8、strcpyfmsg/'hijamclient!");n=send(sockfd/msg/sizeof(msg)/0);n=recv(sockfd/msg/MAX_MSG_SIZE/0);msg[n]=0;printfC^sXn^msg);/*在屏
7、tdio.h>#defineSERVER_PORT8888/*服务端口*/#defineMAX_MSG_SIZE1024/*缓冲区的大小*/intGetServerAddr(char*addrname){printff^Pleaseinputserveraddr:/z);scanf("%s8、strcpyfmsg/'hijamclient!");n=send(sockfd/msg/sizeof(msg)/0);n=recv(sockfd/msg/MAX_MSG_SIZE/0);msg[n]=0;printfC^sXn^msg);/*在屏
8、strcpyfmsg/'hijamclient!");n=send(sockfd/msg/sizeof(msg)/0);n=recv(sockfd/msg/MAX_MSG_SIZE/0);msg[n]=0;printfC^sXn^msg);/*在屏
此文档下载收益归作者所有