资源描述:
《互联网络程序设计实验实验.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验2socket封装1.实验目标以C++类封装socket2.实验原理类继承体系:3.实验内容(1)socket表现为文件描述符将intsocket作为类的成员,类向外暴露各种socket操作编写如下:classSocket{private:intsin_size;intsockfd,new_fd;unsignedshortport;structsockaddr_inmy_addr,their_addr,get_addr;public:Socket();virtual~Socket();virtuali
2、ntSocket();voidSetPort(unsignedshortin_port);boolBind();voidSetRemotePort(unsignedshortin_port);unsignedshortGetRemotePort();//voidGetRemoteAddrees(char*addrees);boolConnect();voidListen();voidAccept();intSend(constchar*buf,intlen);intSendto(constchar*buf
3、,intlen);intRecv(char*buf,intlen);intRecvfrom(char*buf,intlen);voidClose();};classTCP:publicSocket{public:intSocket();boolConnect();};classUDP:publicSocket{public:intSocket();};classSCTP:publicSocket{public:intSocket();boolConnect();};#endifsocket的类型很多AF_
4、INETAF_INET6AF_LOCALSOCK_STREAMTCP
5、SCTPTCP
6、SCTPyesSOCK_DGRAMUDPUDPyesSOCK_SEQPACKETSCTPSCTPyes以一种统一的形式封装各种不同类型的socket处理如下://定义classTCP:publicSocket{public:intSocket();boolConnect();};classUDP:publicSocket{public:intSocket();};classSCTP:publicSocket{public
7、:intSocket();boolConnect();};//函数intUDP::Socket(){sockfd=socket(AF_INET,SOCK_DGRAM,0);returnsockfd;}intTCP::Socket(){sockfd=socket(AF_INET,SOCK_STREAM,0);returnsockfd;}intSCTP::Socket(){sockfd=socket(AF_INET,SOCK_SEQPAKET,0);returnsockfd;}(2)考察socket的连接函数
8、socket的地址族不一样,导致sockaddr结构是不一样的,虽然tcp/sctp这样的面向连接的协议可能都会有connect这样的函数,并且连接的动作都差不多,但是connect函数的servaddr参数是不一样的。如何解决相似动作,但是参数类型不同?处理如下:boolTCP::Connect(){if(connect(sockfd,(structsockaddr*)&their_addr,sizeof(structsockaddr))==-1)returnfalse;returntrue;}bool
9、SCTP::Connect(){if(connect(sockfd,(conststructsockaddr*)&their_addr,sizeof(structsockaddr))==-1)returnfalse;returntrue;}附录1socket.h#ifndefSOCKET__H#defineSOCKET__H#include#include#include#include#include<
10、sys/uio.h>#include#include#include#include#include#include#include#include#include#include#include<