小編給大家分享一下VB.NET Socket編程的示例分析,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供大興網(wǎng)站建設(shè)、大興做網(wǎng)站、大興網(wǎng)站設(shè)計(jì)、大興網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、大興企業(yè)網(wǎng)站模板建站服務(wù),10余年大興做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
下面通過例子來學(xué)習(xí)VB.NET Socket編程類的應(yīng)用,下面的程序分別分服務(wù)器和客戶端兩部分:
ImportsSystem
ImportsSystem.Net
ImportsSystem.Net.Sockets
ImportsSystem.Text
ImportsSystem.Threading
ImportsMicrosoft.VisualBasic
'Stateobjectforreadingclientdataasynchronously
PublicClassStateObject
'Clientsocket.
PublicworkSocketAsSocket=Nothing
'Sizeofreceivebuffer.
PublicConstBufferSizeAsInteger=1024
'Receivebuffer.
Publicbuffer(BufferSize)AsByte
'Receiveddatastring.
PublicsbAsNewStringBuilder
EndClass'StateObject
PublicClassAsynchronousSocketListener
'Threadsignal.
PublicSharedallDoneAsNewManualResetEvent(False)
'Thisserverwaitsforaconnectionandthenusesasychronousoperationsto
'accepttheconnection,getdatafromtheconnectedclient,
'echothatdatabacktotheconnectedclient.
'Itthendisconnectsfromtheclientandwaitsforanotherclient.
PublicSharedSubMain()
'Databufferforincomingdata.
Dimbytes()AsByte=New[Byte](1023){}
'Establishthelocalendpointforthesocket.
DimipHostInfoAsIPHostEntry=DNS.Resolve(Dns.GetHostName())
DimipAddressAsIPAddress=ipHostInfo.AddressList(0)
DimlocalEndPointAsNewIPEndPoint(ipAddress,11000)
'CreateaTCP/IPsocket.
DimlistenerAsNewSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)
'Bindthesockettothelocalendpointandlistenforincomingconnections.
listener.Bind(localEndPoint)
listener.Listen(100)
WhileTrue
'Settheeventtononsignaledstate.
allDone.Reset()
'Startanasynchronoussockettolistenforconnections.
Console.WriteLine("Waitingforaconnection...")
listener.BeginAccept(NewAsyncCallback(AddressOfAcceptCallback),listener)
'Waituntilaconnectionismadeandprocessedbeforecontinuing.
allDone.WaitOne()
EndWhile
EndSub'Main
PublicSharedSubAcceptCallback(ByValarAsIAsyncResult)
'Getthesocketthathandlestheclientrequest.
DimlistenerAsSocket=CType(ar.AsyncState,Socket)
'Endtheoperation.
DimhandlerAsSocket=listener.EndAccept(ar)
'Createthestateobjectfortheasyncreceive.
DimstateAsNewStateObject
state.workSocket=handler
handler.BeginReceive(state.buffer,0,StateObject.
BufferSize,0,NewAsyncCallback(AddressOfReadCallback),state)EndSub'AcceptCallback
PublicSharedSubReadCallback(ByValarAsIAsyncResult)
DimcontentAsString=String.Empty
'Retrievethestateobjectandthehandlersocket
'fromtheasynchronousstateobject.
DimstateAsStateObject=CType(ar.AsyncState,StateObject)
DimhandlerAsSocket=state.workSocket
'Readdatafromtheclientsocket.
DimbytesReadAsInteger=handler.EndReceive(ar)
IfbytesRead>0Then
'Theremightbemoredata,sostorethedatareceivedsofar.
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead))
'Checkforend-of-filetag.Ifitisnotthere,read
'moredata.
content=state.sb.ToString()
Ifcontent.IndexOf("<EOF>")>-1Then
'Allthedatahasbeenreadfromthe
'client.Displayitontheconsole.
Console.WriteLine("Read{0}bytesfromsocket."+vbLf+"Data:{1}",content.Length,content)
'Echothedatabacktotheclient.
Send(handler,content)
Else
'Notalldatareceived.Getmore.
handler.BeginReceive(state.buffer,0,StateObject.
BufferSize,0,NewAsyncCallback(AddressOfReadCallback),state)EndIf
EndIf
EndSub'ReadCallback
PrivateSharedSubSend(ByValhandlerAsSocket,ByValdataAsString)
'ConvertthestringdatatobytedatausingASCIIencoding.
DimbyteDataAsByte()=Encoding.ASCII.GetBytes(data)
'Beginsendingthedatatotheremotedevice.
handler.BeginSend(byteData,0,byteData.
Length,0,NewAsyncCallback(AddressOfSendCallback),handler)EndSub'Send
PrivateSharedSubSendCallback(ByValarAsIAsyncResult)
'Retrievethesocketfromthestateobject.
DimhandlerAsSocket=CType(ar.AsyncState,Socket)
'Completesendingthedatatotheremotedevice.
DimbytesSentAsInteger=handler.EndSend(ar)
Console.WriteLine("Sent{0}bytestoclient.",bytesSent)
handler.Shutdown(SocketShutdown.Both)
handler.Close()
'Signalthemainthreadtocontinue.
allDone.Set()
EndSub'SendCallback
EndClass'AsynchronousSocketListener
看完了這篇文章,相信你對“VB.NET Socket編程的示例分析”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
標(biāo)題名稱:VB.NETSocket編程的示例分析
轉(zhuǎn)載來于:http://www.rwnh.cn/article42/ihjjhc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、做網(wǎng)站、、關(guān)鍵詞優(yōu)化、服務(wù)器托管、網(wǎng)站營銷
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)