资源描述:
《网络编程的设计与实现》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验五、网络编程的设计与实现一.实验目的:通过该实验掌握最基本的Client/Server(客户机/服务器)模式的网络编程技术,并在此基础上实现更为复杂的网络编程。二.任务要求:1、按所附的参考程序使用VC++或其他工具设计出程序()2、在第1步的基础上使用VC++或其他工具设计出一个能实现两个人聊天的网络程序三.实验环境:Windows平台,VC++四.实验内容:#include#include#include#defineMAXSIZE100#pragmacomment(lib,"ws2_32.lib")voidma
2、in(){charsendbuf[MAXSIZE],s[MAXSIZE];charrecvbuf[MAXSIZE];sockaddr_inservice;SOCKETAcceptSocket;SOCKETserver;WSADATAwsaData;intbytesSend,bytesRecv;//初始化intiResult=WSAStartup(MAKEWORD(2,2),&wsaData);if(iResult!=NO_ERROR)printf("ErroratWSAStartup()");//建立socketserver=socket(AF_INET,SOCK_STREAM
3、,IPPROTO_TCP);if(server==INVALID_SOCKET){printf("Erroratsocket():%ld",WSAGetLastError());WSACleanup();return;}//绑定socketservice.sin_family=AF_INET;service.sin_addr.s_addr=inet_addr("127.0.0.1");service.sin_port=htons(27016);if(bind(server,(SOCKADDR*)&service,sizeof(service))==SOCKET_ERROR){p
4、rintf("bind()failed.");closesocket(server);return;}//监听socketif(listen(server,1)==SOCKET_ERROR)printf("Errorlisteningonsocket.");//接受连接printf("Waitingforaclienttoconnect...");AcceptSocket=SOCKET_ERROR;while(AcceptSocket==SOCKET_ERROR){AcceptSocket=accept(server,NULL,NULL);}printf("Client
5、Connected.");server=AcceptSocket;strcpy(recvbuf,"");bytesRecv=recv(server,recvbuf,MAXSIZE,0);if(bytesRecv==0
6、
7、bytesRecv==WSAECONNRESET){printf("ConnectionClosed.");return;}strcpy(sendbuf,"欢迎访问服务器!!");if(bytesSend=send(server,sendbuf,strlen(sendbuf),0)==SOCKET_ERROR){printf("发送数据出错");return
8、;}while(1){memset(recvbuf,' ',sizeof(recvbuf));printf("服务器:");gets(s);if(bytesSend=send(server,s,strlen(s),0)==SOCKET_ERROR){printf("发送数据出错");return;}if(recv(server,recvbuf,sizeof(recvbuf),0)==SOCKET_ERROR){printf("接收数据出错");return;}inti=0;printf("客户:");puts(recvbuf);}closesocket(server);WSACl
9、eanup();}再编一个client程序:#include#include#include#defineMAXSIZE100#pragmacomment(lib,"ws2_32.lib")voidmain(){//初始化Winsock.WSADATAwsaData;charsendbuf[MAXSIZE],s[MAXSIZE];charrecvbuf[MAXSIZE];SOCKETclient;socka