千家信息网

VB.NET Socket编程的示例分析

发表于:2025-02-23 作者:千家信息网编辑
千家信息网最后更新 2025年02月23日,小编给大家分享一下VB.NET Socket编程的示例分析,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!下面通过例子来学习VB.NET Socket编程类的应用,下面的程序分别分服务
千家信息网最后更新 2025年02月23日VB.NET Socket编程的示例分析

小编给大家分享一下VB.NET Socket编程的示例分析,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

下面通过例子来学习VB.NET Socket编程类的应用,下面的程序分别分服务器和客户端两部分:

  1. ImportsSystem

  2. ImportsSystem.Net

  3. ImportsSystem.Net.Sockets

  4. ImportsSystem.Text

  5. ImportsSystem.Threading

  6. ImportsMicrosoft.VisualBasic

  7. 'Stateobjectforreadingclientdataasynchronously

  8. PublicClassStateObject

  9. 'Clientsocket.

  10. PublicworkSocketAsSocket=Nothing

  11. 'Sizeofreceivebuffer.

  12. PublicConstBufferSizeAsInteger=1024

  13. 'Receivebuffer.

  14. Publicbuffer(BufferSize)AsByte

  15. 'Receiveddatastring.

  16. PublicsbAsNewStringBuilder

  17. EndClass'StateObject

  18. PublicClassAsynchronousSocketListener

  19. 'Threadsignal.

  20. PublicSharedallDoneAsNewManualResetEvent(False)

  21. 'Thisserverwaitsforaconnectionandthenusesasychronousoperationsto

  22. 'accepttheconnection,getdatafromtheconnectedclient,

  23. 'echothatdatabacktotheconnectedclient.

  24. 'Itthendisconnectsfromtheclientandwaitsforanotherclient.

  25. PublicSharedSubMain()

  26. 'Databufferforincomingdata.

  27. Dimbytes()AsByte=New[Byte](1023){}

  28. 'Establishthelocalendpointforthesocket.

  29. DimipHostInfoAsIPHostEntry=Dns.Resolve(Dns.GetHostName())

  30. DimipAddressAsIPAddress=ipHostInfo.AddressList(0)

  31. DimlocalEndPointAsNewIPEndPoint(ipAddress,11000)

  32. 'CreateaTCP/IPsocket.

  33. DimlistenerAsNewSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)

  34. 'Bindthesockettothelocalendpointandlistenforincomingconnections.

  35. listener.Bind(localEndPoint)

  36. listener.Listen(100)

  37. WhileTrue

  38. 'Settheeventtononsignaledstate.

  39. allDone.Reset()

  40. 'Startanasynchronoussockettolistenforconnections.

  41. Console.WriteLine("Waitingforaconnection...")

  42. listener.BeginAccept(NewAsyncCallback(AddressOfAcceptCallback),listener)

  43. 'Waituntilaconnectionismadeandprocessedbeforecontinuing.

  44. allDone.WaitOne()

  45. EndWhile

  46. EndSub'Main

  47. PublicSharedSubAcceptCallback(ByValarAsIAsyncResult)

  48. 'Getthesocketthathandlestheclientrequest.

  49. DimlistenerAsSocket=CType(ar.AsyncState,Socket)

  50. 'Endtheoperation.

  51. DimhandlerAsSocket=listener.EndAccept(ar)

  52. 'Createthestateobjectfortheasyncreceive.

  53. DimstateAsNewStateObject

  54. state.workSocket=handler

  55. handler.BeginReceive(state.buffer,0,StateObject.
    BufferSize,0,NewAsyncCallback(AddressOfReadCallback),state)

  56. EndSub'AcceptCallback

  57. PublicSharedSubReadCallback(ByValarAsIAsyncResult)

  58. DimcontentAsString=String.Empty

  59. 'Retrievethestateobjectandthehandlersocket

  60. 'fromtheasynchronousstateobject.

  61. DimstateAsStateObject=CType(ar.AsyncState,StateObject)

  62. DimhandlerAsSocket=state.workSocket

  63. 'Readdatafromtheclientsocket.

  64. DimbytesReadAsInteger=handler.EndReceive(ar)

  65. IfbytesRead>0Then

  66. 'Theremightbemoredata,sostorethedatareceivedsofar.

  67. state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead))

  68. 'Checkforend-of-filetag.Ifitisnotthere,read

  69. 'moredata.

  70. content=state.sb.ToString()

  71. Ifcontent.IndexOf("<EOF>")>-1Then

  72. 'Allthedatahasbeenreadfromthe

  73. 'client.Displayitontheconsole.

  74. Console.WriteLine("Read{0}bytesfromsocket."+vbLf+"Data:{1}",content.Length,content)

  75. 'Echothedatabacktotheclient.

  76. Send(handler,content)

  77. Else

  78. 'Notalldatareceived.Getmore.

  79. handler.BeginReceive(state.buffer,0,StateObject.
    BufferSize,0,NewAsyncCallback(AddressOfReadCallback),state)

  80. EndIf

  81. EndIf

  82. EndSub'ReadCallback

  83. PrivateSharedSubSend(ByValhandlerAsSocket,ByValdataAsString)

  84. 'ConvertthestringdatatobytedatausingASCIIencoding.

  85. DimbyteDataAsByte()=Encoding.ASCII.GetBytes(data)

  86. 'Beginsendingthedatatotheremotedevice.

  87. handler.BeginSend(byteData,0,byteData.
    Length,0,NewAsyncCallback(AddressOfSendCallback),handler)

  88. EndSub'Send

  89. PrivateSharedSubSendCallback(ByValarAsIAsyncResult)

  90. 'Retrievethesocketfromthestateobject.

  91. DimhandlerAsSocket=CType(ar.AsyncState,Socket)

  92. 'Completesendingthedatatotheremotedevice.

  93. DimbytesSentAsInteger=handler.EndSend(ar)

  94. Console.WriteLine("Sent{0}bytestoclient.",bytesSent)

  95. handler.Shutdown(SocketShutdown.Both)

  96. handler.Close()

  97. 'Signalthemainthreadtocontinue.

  98. allDone.Set()

  99. EndSub'SendCallback

  100. EndClass'AsynchronousSocketListener

看完了这篇文章,相信你对"VB.NET Socket编程的示例分析"有了一定的了解,如果想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!

0