资源描述:
《网络编程指南设计-v0.4》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、实用文案计算机网络编程1.简单的TCP程序的建立TCP客户端TCP服务器端创建套接字socketBind服务器端口Listen监听端口Accept客户端链接Read/Write数据创建套接字socketConnect服务器Read/Write数据图1-1TCP整体程序示意图TCP/IP通用套接字地址结构structsockaddr{sa_family_tsa_family;charsa_data[14];}IPv4特定套接字地址结构structsockaddr_in{sa_family_tsin_family;in_port_tsin_port;structin_addrsin_a
2、ddr;unsignedcharsin_zero[8];}图1-2套接字地址结构1.1服务器端程序/*相关头文件*/#include#include标准文档实用文案#include#include#includeintsockfd=socket(AF_INET,SOCK_STREAM,0);structsockaddr_inserveraddr,clientaddr;serveraddr.sin_family=AF_INET;serveraddr.sin_port=ht
3、ons(1234);serveraddr.sin_addr.s_addr=INADDR_ANY;socklen_taddrlen=sizeof(addr);bind(sockfd,(structsockaddr*)&serveraddr,addrlen);/*被动套接字,两个队列*/listen(sockfd,5);intsock_id=accept(sockfd,(structsockaddr*)&clientaddr,&addrlen);/*为什么是写sock_id?已链接的套接字是否可以写sockfd?监听套接字*/write(sock_id,buf,strlen(buf))
4、;Close(sockf_id);1.2客户端程序#include#include#include#include#includeintsockfd=socket(AF_INET,SOCK_STREAM,0);structsockaddr_inaddr;addr.sin_family=AF_INET;addr.sin_port=htons(1234);inet_pton(AF_INET,"127.0.0.1",&addr.sin_addr);connect(soc
5、kfd,(structsockaddr*)&addr,sizeof(addr));charrecvBuf[100]={0};read(sockfd,recvBuf,sizeof(recvBuf));Close(sockfd);1.简单的UDP程序的建立标准文档实用文案服务器端客户端创建socketBind端口Recvfrom读取数据创建socketSendto发送数据图2-1UDP程序整体架构2.1服务端程序intsockfd=socket(AF_INET,SOCK_DGRAM,0);structsockaddr_inservaddr;servaddr.sin_family=AF_
6、INET;servaddr.sin_port=htons(1234);servaddr.sin_addr.s_addr=INADDR_ANY;bind(sockfd,(structsockaddr*)&servaddr,sizeof(servaddr));structsockaddr_incliaddr;socklen_tclilen=sizeof(cliaddr);recvfrom(sockfd,msg,sizeof(msg),0,(structsockaddr*)&cliaddr,&clilen);2.2客户端程序intsockfd=socket(AF_INET,SOCK_DG
7、RAM,0);structsockaddr_inservaddr;servaddr.sin_family=AF_INET;servaddr.sin_port=htons(1234);inet_pton(AF_INET,"127.0.0.1",&servaddr.sin_addr);//没有客户端与服务器之分Structsockaddr_inmyaddr;myaddr.sin_family=AF_INET;Myaddr.sin_port=htons(1234);Myad