VB.NET Socket编程的示例分析
小编给大家分享一下VB.NET Socket编程的示例分析,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
下面通过例子来学习VB.NET Socket编程类的应用,下面的程序分别分服务器和客户端两部分:
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编程的示例分析”有了一定的了解,如果想了解更多相关知识,欢迎关注编程网行业资讯频道,感谢各位的阅读!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341