异步Socket通信经典案例教程
异步Socket通信经典案例教程Socket client-listener EndAccept(ar)1lDone SetOStateObject statteObject Ostate, work Socket client/远端信息Endpoint tempremoteeP= client. RemoteEndPointIPEndPoint tempRemateTP=( TPEnd Foint )tempRemotelPstring reupip-LepRemoteIP Address ToString(string remoport-tepRemoteIP Port ToString OI PHostEntry host= Dns. GetHostByAddress(tempRemoteIP Addressstring hostname= host host narstatusbar1. Panels「11.Text-"接受「"+ HostName+"repp+":"+ remoport+"远程计算机正确连接!Add("[+hostreplyclient. Begin(state. buff(bject Buffer Size, 0allback(readcallback异步接收回调函数public void readCallback(IAsyncResult arSocket handler state work SocketbytesRead- handler endreCar)f( bytringstrmsg-Encoding. ASCII GetString(state buffer, O, bytesRead)STastring cont//远端信息EndPoint tempRemoteEP- handler. ReloteEndPointIPEndPoint tempRemoteIP=( IPEndPoint )tempRemoteEPstring rempip=temp Remote IP Address. ToString(string remoport-tempRemoteIP Port ToString ()IPHostEntry host= Dns Get Host By Address(t. empRemotell. AddressHostxhost, hostastatusBar1. Panels[1].Toxt="正在接收["+ HostName+"+ reply+":"+ europort+"的信息.string time- DateTime. Now ToSlistboxRecv. Items. Add("("+time+")+HostName+ems. Add (striif(cont ent. IndexOf(\x9 9\x9 9)>1)statusBar1. Panels」.Text-"信息接收完毕!//接收到完整的信息Messagebox.Show("接收到:"+ content);string mSg-poweryd. CodeParse(content)end( handler,msg);//异步发送/用单独的 socke+发送handler.BeginReceive(staLe buffer, 0, StateObject BufferSize, 0new AsyncCallback(readCallback), state)异步发送ingel byteData=Encoding. ASCII. Get Bytes(dathandler. BegilSend (bvteData, 0, byteData Length, 0new Async Callback(SendCallback), handler)handler. Send(byteDataeglon/用单独的 socket发送d Send (string data)this, txtRemoip. textt=this. txtremoport TextIPAddress serverIp- IPAddress Parse (ip)nt serverport-CI PEndFoint. iep=new I PEndPoint (serverIp, serverPort iSocket(AddressFamilv. InterNetwork, SocketType. Stream, Protocol Type Tcpsocket Connect (iep)hotel] byt eMes sage=Encoding. ASC I I GetByt es (dat. a)ket. Send (by LeMesocket. Shutdown(SocketShutdown. Bothsocket. Closewendregion/异步发送回调函数/异步发送回调函数private static void SendCallback(IAsyncResult arSocket handlerint bytes Sent=handler. EndSend (arMessageBox.Show(“发送成功!")handler. Shutdown(SocketShutdown. Both)handler. ClosecatMessageBox. Show(ex ToString()private void btnListen Click(obiect sender, Syst em. Event Args e)th= new Thread( new Threadstart( Listen);/以 Listen过程来初始化线程实例th. Start0;//启动此线程this. binListen Enabled=falseprivate void btnClosenet Click(object sender, System. EventArgs e,trlistenerrun= falseth Abortlistener. Close)statusBar1. Panels[0].Toxt="与客户端断开连接!statusBar. Panels[1l.TextcatchMessageBox.Show("连接尚未建立,断开无效!","警告")private void btnExit Click (object sender, System. EventArgs e)tlistenerrun = falseth Abortth- nulllistener. Close Ostatusbar1. Panels[0].Text=“与客户端断开连接!"statusBarl Panels[1. Texl=Itch(Exceptlicatio Exito/异步传递的状态对象plass Stateobiectpublic socket workSocket- nullpublic const int Buffersizepublic byte] bufferbvtelBufferSize]public StringBuilder sbBuilder客户端(同步发送并接收):lIsing SvStemUSIngusing Systcm. ThreadSocket socketint numbe-1024:/次接收到的字节数private void btnConnect Click(object sender, System. EventArgs e)ttring ip-this txt IP. testring port=this txtRrt TextIPAddress serverIp-IPAddress Parse(ip)Port=Convert. ToInt32(poIPEndPoint icp=ncw IPEndPoint(scrvcrlp, scrvcrPortPHostEntry host= Dns. GetHostByAddress(iep Addressstring HostnAme- host. IlostNameSocket (Addressfamilv. InterNetwork, SocketIype. Stream, Protocol'Iype Tcpsocket Connect (ieIPEndPoint tempRemoteTP=( TPEnd Point )socket. L. l EndPointstatusBarl. Panelslo. Text-51tg口:"+ tempRemoteIP.Port. ToString+"正在临听.与远程计算机["+ Host Name+"]"+port+"建立连接catchstatusBar1. Panels[0].Text="无法连接到目标计算机!#byt eMcssagc=Encoding. ASCII. GctBytcs(text Box1. Text+99)socket Send(byt mEssagehotell bytes new byte [1024string str=Encoding Default. Get String(bytes)how("接收到socket. Shutdown(SocketShutdown. Bothfendregionprivate void btnSend Click(obnder, Systel eventAtrstatusBar1. Panels[1].Text="正在发送信息!"string message-this. txtsend TextSend info(messagecatch//异常处理statusBar1. Panels[0.Text="无法发送信息到目标计算机!private void Send Info(string message)string ip=this. txtip Textstring port=this. txtport ToxtIPAddress serverIp=IPAddress Parse (ip)int serverPort=Convert ToInt. 32(port.IPEndPoint iep=new IPEndPoint(serverIp, serverPurt)bytel byteMes sagesocket=newSocket(AddressFamlily InterNelwork, SocketType Streall, Protocol Type Tcp)socket Connect (iep)fendregibytel] byteMessage-Encoding ASCII Get Bytes(message+\x99\x99")socket Send(bytcMessago远端信息EndPoint tempRemot eEP- socket Remot eEndPointIPEndl'ointt.empRemotell=(IPEndl'oint )tempRemot eePstring rempip=tempRemoteIP Address ToString(string remoport=tempRemoteIP Port ToStringIPHostEntry host= Dns. GetHostByAddress(tempRemoteIP Addresstring HostName- host. Ho//发送信息string time1= Date Time Now. ToString(listboxsend. IHostNamc +":"listboxscnd Itoms Add (mcssagc//发送完了,直接接收Stringbuilder sb- new StringBuildehile(truestatusBar1. Panels[1].Tex-"正在等待接收信息."bytel bytes= new byte []int rccvbytcs=socket. Rcccivc(bytesstring strmsg1lt. Getstring time2= DateTime. Now ToString(listboxRecy Items Add+host\atsb. Append (strmsgif(sb. ToString(. IntbreakstatusBar1. Panels[1].Text="接收信息完毕!"代码解码CodeParse(sb. ToString oket. Shutdown( SocketshutBoth)e o
用户评论