服务器
struct sockaddr_in sockaddr;
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr =htonl(innaddr_any) //inet_addr("192.168.1.5") ;
sockaddr.sin_port = htons(80);
socklen_t len=sizeof(sockaddr);
struct sockaddr_in sockaddrClient;
int sock =socket(AF_INET,SOCK_STREAM,0);
bind(sock,&sockaddr,sizeof(sockaddr)/len);//return 0 or -1
listen(sock,QCount);//QCount为int型最大监听数
int acceptSock=accept(sock,&sockaddrClient,&len);
客户端 connect(sock,&addr,len);
recv(acceptSock,buf,nbytes,flags)send(acceptSock,buf,nbytes,flags)
recvfrom/recvmsgsendto/sendmsg
如果是IO模型,则在listen和accept之间添加select /poll/epoll函数,然后检测返回值
对于epoll
//epoll初始化
int nfds;
int m_pj_epollfd = epoll_create(PJ_MAXFD);
struct epoll_event m_pj_epollev[PJ_MAXFD];
//添加socket
ev.data.fd = sock;
ev.events = EPOLLIN|EPOLLET;
epoll_ctl(m_pj_epollfd, EPOLL_CTL_ADD, sock, &ev);
listen(sock,MAX);
while(1)
{
nfds = epoll_wait(m_pj_epollfd, m_pj_epollev, PJ_MAXFD, -1); //事件数
for(i=0;i<nfds;i++)
{
int sockfd = m_pj_epollev[i].data.fd;//事件
epoll_event _event = m_pj_epollev[i];
//分别处理
if(sock==sockfd){ ... accpet(sockfd);//...再添加socket
}
elseif(_event.events&EPOLLIN){..... recv(sock)....;}//处理socket
else;
}
}