文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

VB.NET Socket编程的示例分析

2023-06-17 20:46

关注

小编给大家分享一下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.  

  8. 'Stateobjectforreadingclientdataasynchronously  

  9.  

  10. PublicClassStateObject  

  11. 'Clientsocket.  

  12. PublicworkSocketAsSocket=Nothing 

  13. 'Sizeofreceivebuffer.  

  14. PublicConstBufferSizeAsInteger=1024 

  15. 'Receivebuffer.  

  16. Publicbuffer(BufferSize)AsByte  

  17. 'Receiveddatastring.  

  18. PublicsbAsNewStringBuilder  

  19. EndClass'StateObject  

  20.  

  21.  

  22. PublicClassAsynchronousSocketListener  

  23. 'Threadsignal.  

  24. PublicSharedallDoneAsNewManualResetEvent(False)  

  25.  

  26. 'Thisserverwaitsforaconnectionandthenusesasychronousoperationsto  

  27. 'accepttheconnection,getdatafromtheconnectedclient,  

  28. 'echothatdatabacktotheconnectedclient.  

  29. 'Itthendisconnectsfromtheclientandwaitsforanotherclient.  

  30. PublicSharedSubMain()  

  31. 'Databufferforincomingdata.  

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

  33.  

  34. 'Establishthelocalendpointforthesocket.  

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

  36. DimipAddressAsIPAddress=ipHostInfo.AddressList(0)  

  37. DimlocalEndPointAsNewIPEndPoint(ipAddress,11000)  

  38.  

  39. 'CreateaTCP/IPsocket.  

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

  41.  

  42. 'Bindthesockettothelocalendpointandlistenforincomingconnections.  

  43. listener.Bind(localEndPoint)  

  44. listener.Listen(100)  

  45.  

  46. WhileTrue  

  47. 'Settheeventtononsignaledstate.  

  48. allDone.Reset()  

  49.  

  50. 'Startanasynchronoussockettolistenforconnections.  

  51. Console.WriteLine("Waitingforaconnection...")  

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

  53.  

  54. 'Waituntilaconnectionismadeandprocessedbeforecontinuing.  

  55. allDone.WaitOne()  

  56. EndWhile  

  57. EndSub'Main  

  58.  

  59.  

  60. PublicSharedSubAcceptCallback(ByValarAsIAsyncResult)  

  61. 'Getthesocketthathandlestheclientrequest.  

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

  63. 'Endtheoperation.  

  64. DimhandlerAsSocket=listener.EndAccept(ar)  

  65.  

  66. 'Createthestateobjectfortheasyncreceive.  

  67. DimstateAsNewStateObject  

  68. state.workSocket=handler 

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

  70. EndSub'AcceptCallback  

  71.  

  72.  

  73. PublicSharedSubReadCallback(ByValarAsIAsyncResult)  

  74. DimcontentAsString=String.Empty  

  75.  

  76. 'Retrievethestateobjectandthehandlersocket  

  77. 'fromtheasynchronousstateobject.  

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

  79. DimhandlerAsSocket=state.workSocket  

  80.  

  81. 'Readdatafromtheclientsocket.  

  82. DimbytesReadAsInteger=handler.EndReceive(ar)  

  83.  

  84. IfbytesRead>0Then  

  85. 'Theremightbemoredata,sostorethedatareceivedsofar.  

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

  87.  

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

  89. 'moredata.  

  90. content=state.sb.ToString()  

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

  92. 'Allthedatahasbeenreadfromthe  

  93. 'client.Displayitontheconsole.  

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

  95. 'Echothedatabacktotheclient.  

  96. Send(handler,content)  

  97. Else  

  98. 'Notalldatareceived.Getmore.  

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

  100. EndIf  

  101. EndIf  

  102. EndSub'ReadCallback  

  103.  

  104. PrivateSharedSubSend(ByValhandlerAsSocket,ByValdataAsString)  

  105. 'ConvertthestringdatatobytedatausingASCIIencoding.  

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

  107.  

  108. 'Beginsendingthedatatotheremotedevice.  

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

  110. EndSub'Send  

  111.  

  112. PrivateSharedSubSendCallback(ByValarAsIAsyncResult)  

  113. 'Retrievethesocketfromthestateobject.  

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

  115.  

  116. 'Completesendingthedatatotheremotedevice.  

  117. DimbytesSentAsInteger=handler.EndSend(ar)  

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

  119.  

  120. handler.Shutdown(SocketShutdown.Both)  

  121. handler.Close()  

  122. 'Signalthemainthreadtocontinue.  

  123. allDone.Set()  

  124. EndSub'SendCallback  

  125. EndClass'AsynchronousSocketListener 

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

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     801人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     348人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     311人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     432人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     220人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯