一、在initinstance中加入:
word wversionrequested;
wsadata wsadata;
int err;
wversionrequested = makeword( 2, 2 );
err = wsastartup( wversionrequested, &wsadata );
if ( err != 0 )
if ( lobyte( wsadata.wversion ) != 2 ||
hibyte( wsadata.wversion ) != 2 )
二、在oninitdialog中加入:
m_socket=wsasocket(af_inet,sock_dgram,0,null,0,0);
if(invalid_socket==m_socket)
sockaddr_in addrsock;
addrsock.sin_addr.s_un.s_addr=htonl(inaddr_any);
addrsock.sin_family=af_inet;
addrsock.sin_port=htons(6000);
if(socket_error==bind(m_socket,(sockaddr*)&addrsock,sizeof(sockaddr)))
if(socket_error==wsaasyncselect(m_socket,m_hwnd,um_sock,fd_read))
return true;
三、#define um_sock wm_user+1
四、響應um_sock訊息:
onsock(wparam wparam,lparam lparam)
phost=gethostbyaddr((char*)&addrfrom.sin_addr.s_un.s_addr,4,af_inet);
//str.format("%s說 :%s",inet_ntoa(addrfrom.sin_addr),wsabuf.buf);
str.format("%s說 :%s",phost->h_name,wsabuf.buf);
str+="/r/n";
getdlgitemtext(idc_edit_recv,strtemp);
str+=strtemp;
setdlgitemtext(idc_edit_recv,str);
break;}}
五、傳送處:
dword dwip;
cstring strsend;
wsabuf wsabuf;
dword dwsend;
int len;
cstring strhostname;
sockaddr_in addrto;
hostent* phost;
if(getdlgitemtext(idc_edit_hostname,strhostname),strhostname=="")
else
addrto.sin_family=af_inet;
addrto.sin_port=htons(6000);
getdlgitemtext(idc_edit_send,strsend);
len=strsend.getlength();
wsabuf.buf=strsend.getbuffer(len);
wsabuf.len=len+1;
setdlgitemtext(idc_edit_send,"");
if(socket_error==wsasendto(m_socket,&wsabuf,1,&dwsend,0,
(sockaddr*)&addrto,sizeof(sockaddr),null,null))
vc非同步套接字
mfc 建立非同步套接字的網路聊天程式 1.首先包含 winsock2.h 2.工程 設定 鏈結 ws2 32.lib 4.dlg類中 加入socket m sock,cstring recvbuf成員 並且寫下此 bool cchat16dlg initsocket sockaddr in add...
非同步套接字
wsadata wsa wsastartup makeword 2,2 wsa socket fdserver socket af inet,sock stream,ipproto tcp struct sockaddr in server server.sin family af inet ser...
非同步套接字程式設計
部分說明 define um sock wm user 1 on message um sock onsock afx msg void onsock wparam wparam lparam lparam bool cmydlg initsocket sockaddr in addrsock ad...