VB.NET Socket编程的示例分析

发布时间:2021-12-02 11:24:33 作者:小新
阅读:446
开发者专用服务器限时活动,0元免费领! 查看>>

小编给大家分享一下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编程的示例分析”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:
  1. VB.NET文件对象的示例分析
  2. VB.NET处理数据行的示例分析

开发者交流群:

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vb.net socket

上一篇:Kubernetes怎样部署Nebula图数据库集群

下一篇:tk.Mybatis插入数据获取Id怎么实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》
开发者交流群×