《scoket编程(一对多).docx》由会员分享,可在线阅读,更多相关《scoket编程(一对多).docx(11页珍藏版)》请在第壹文秘上搜索。
1、scoket编程(一对多)serverDIg.h文件IllllllllllllllllllllllllllllllllllllllllllllllllllllllinIiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiipublic:/接受到的消息CListBoxm_edMSg;/发送的消息CEditm_edSend;CStringm_strSend;/套接字SOCKETsock;/套接字数组,用来一对多SOCKETmsgsock50;/客户段套接字SOCKETclisock;/地址簇长度intm_nAddlen;/地址簇SockaddrJnserv;intm_nCount;pub
2、lic:/获取空闲的SOCKET数组号intgetcount();/向所有的客户端发送消息voidsendtoall(SOCKETzchar*);/Illlllllllllllllllllllllllllllllllllllllllllllllllin.cpp文件1、在server.cpp中初始化socket2、在构造函数中初始化套接字数组:for(inti=0;iEnableWindow(FALSE);/创建SOCKETsock=socket(AFJNETzSOCK_STREAM/*SOCK_DGRAM*/,0);绑定if(bind(sockz(sockaddr*)8iservzm-nAdd
3、len)(intnError=GetLastErrorO;m_edMSg.AddString(_T(绑定失败!);)elsem_edMSg.AddString(_T(创建服务器成功!);listen(sock,5);/创建服务器线程AfxBeginThread(8iServerThreadz0);)4、服务器线程函数/服务器线程函数UINTServerThread(LPVOID)(CStringStrText;USES_CONVERSION;charbuff100=0;CSizesize;size.c=O;size.cy=30;intS=LmSgCOUnt,IooP=LfIag=O;/CSer
4、verDIg*dig(CServerDlg*)AfGetMainWnd()-GetSafeHwnd();CServerDIg*dig(CServerDlg*)AfxGetApp()-GetMainWnd();if(dig=NULL)return-1;msgcount=dlg-getcount();if(msgcount=-1)loop=O;if(loop)S=1;dlg-msgsockmsgcount=accept(dlg-sockz(sockaddr*)8i(dlg-serv)x(dlg-m-nAddlen);if(dlg-msgsockmsgcount=INVALID_SOCKET)(in
5、tnError=GetLastErrorO;dlg-m_edMSg.AddString(_T(accpetfailed);)else(AfxBegiThread(ServerThreadz0);dig-SetForegroundWindowO;dlg-m_edMSg.AddString(_T(,n);dlg-m_edMSg.AddString(_T(连接!);s=recv(dlg-msgsockmsgcountzbuff100z0);StrText=inet_ntoa(dlg-serv.sin_addr);dlg-m-edMSg.AddString(*strText*A2W(buff);dlg
6、-GetDlgItem(IDC_BUTTON_SEND)-EnableWindow(TRUE);while(s!=SOCKET.ERROR)/循环接收数据s=recv(dlg-msgsockmsgcountzbuft100z0);dig-SetForegroundWindowO;if(s!=SOCKET_ERROR)dlg-m_edMSg.AddString(A2W(buff);dlg-sendtoall(dlg-msgsockmsgcount,buff);)send(dlg-msgsockmsgcountzDisconnected,100z0);dig-m_edMSg.AddString(_
7、T(Disconnected);dig-msgsockmsgcout=NULL;for(inti=0;imsgsocki!=NULL)flag=l;if(flag!=1)(dlg-GetDlgItem(IDC_BUTTON_SEND)-EnableWindow(FALSE);)closesocket(dlg-msgsockmsgcount);)终止线程AfxEndThread(O);return0;5、发送消息/获取没使用的SOCKET数组号intCServerDlg:getcount()(for(inti=0;i50;i+)if(msgsocki=NULL)returni;)return-1;voidCServerDlg:sendtoall(SOCKETszchar*buffer)(for(inti=0;iGetMainWndO;if(dig=NULL)return-1;dlg-GetDlgItem(IDC_BUTTON_CONNET)-EnableWindow(FALSE);dlg-GetDlgItem(IDC_BUTTON_CLOSE)-EnableWindow(FALSE);/连接服务器while(connect(dlg-clisockz(sockaddr*)8i(dlg-cli)xsizeof(dlg-cli)&dlg-m_nEe