Example Analysis of VB.NET Socket programming
Editor to share with you a sample analysis of VB.NET Socket programming, I hope you will gain something after reading this article, let's discuss it together!
Here is an example to learn the application of the VB.NET Socket programming class. The following program is divided into two parts: the server and the client.
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 (") >-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
After reading this article, I believe you have some understanding of "sample Analysis of VB.NET Socket programming". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!