千家信息网

VB.NET中Socket编程类怎么用

发表于:2024-09-22 作者:千家信息网编辑
千家信息网最后更新 2024年09月22日,小编给大家分享一下VB.NET中Socket编程类怎么用,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!一直以来很想学习Socket编程方面的应用,比如怎样通过Socket编程实现单片
千家信息网最后更新 2024年09月22日VB.NET中Socket编程类怎么用

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

一直以来很想学习Socket编程方面的应用,比如怎样通过Socket编程实现单片机与PC的TCP连接通信。在单片机嵌入网卡芯片与PC进行连接通信,实现PC的web方式对单片机所控制的设备的状态管理,例如智能家居方面的应用。

下面通过例子来学习VB.NET Socket编程类的应用,下面的程序是服务器中的代码实现:

Visual Basic ---tcpserver

  1. Imports System

  2. Imports System.Net

  3. Imports System.Net.Sockets

  4. Imports System.Text

  5. Imports System.Threading

  6. Imports Microsoft.VisualBasic

  7. ' State object for reading client
    data asynchronously

  8. Public Class StateObject

  9. ' Client socket.

  10. Public workSocket As Socket = Nothing

  11. ' Size of receive buffer.

  12. Public Const BufferSize As Integer = 1024

  13. ' Receive buffer.

  14. Public buffer(BufferSize) As Byte

  15. ' Received data string.

  16. Public sb As New StringBuilder

  17. End Class 'StateObject

  18. Public Class AsynchronousSocket
    Listener

  19. ' Thread signal.

  20. Public Shared allDone As New Manual
    ResetEvent(False)

  21. ' This server waits for a connection
    and then uses asychronous operations to

  22. ' accept the connection, get data from
    the connected client,

  23. ' echo that data back to the
    connected client.

  24. ' It then disconnects from the
    client and waits for another client.

  25. Public Shared Sub Main()

  26. ' Data buffer for incoming data.

  27. Dim bytes() As Byte = New [Byte](1023) {}

  28. ' Establish the local endpoint for the socket.

  29. Dim ipHostInfo As IPHostEntry =
    Dns.Resolve(Dns.GetHostName())

  30. Dim ipAddress As IPAddress =
    ipHostInfo.AddressList(0)

  31. Dim localEndPoint As New IPEndPoint
    (ipAddress, 11000)

  32. ' Create a TCP/IP socket.

  33. Dim listener As New Socket(AddressFamily.
    InterNetwork, SocketType.Stream, ProtocolType.Tcp)

  34. ' Bind the socket to the local endpoint
    and listen for incoming connections.

  35. listener.Bind(localEndPoint)

  36. listener.Listen(100)

  37. While True

  38. ' Set the event to nonsignaled state.

  39. allDone.Reset()

  40. ' Start an asynchronous socket to listen
    for connections.

  41. Console.WriteLine("Waiting for a connection...")

  42. listener.BeginAccept(New AsyncCallback
    (AddressOf AcceptCallback), listener)

  43. ' Wait until a connection is made and
    processed before continuing.

  44. allDone.WaitOne()

  45. End While

  46. End Sub 'Main

  47. Public Shared Sub AcceptCallback(ByVal ar
    As IAsyncResult)

  48. ' Get the socket that handles the client request.

  49. Dim listener As Socket = CType(ar.AsyncState, Socket)

  50. ' End the operation.

  51. Dim handler As Socket = listener.EndAccept(ar)

  52. ' Create the state object for the async receive.

  53. Dim state As New StateObject

  54. state.workSocket = handler

  55. handler.BeginReceive(state.buffer, 0, StateObject.
    BufferSize, 0, New AsyncCallback(AddressOf
    ReadCallback), state)

  56. End Sub 'AcceptCallback

  57. Public Shared Sub ReadCallback(ByVal ar As
    IAsyncResult)

  58. Dim content As StringString = String.Empty

  59. ' Retrieve the state object and the handler socket

  60. ' from the asynchronous state object.

  61. Dim state As StateObject = CType(ar.AsyncState,
    StateObject)

  62. Dim handler As Socket = state.workSocket

  63. ' Read data from the client socket.

  64. Dim bytesRead As Integer = handler.EndReceive(ar)

  65. If bytesRead > 0 Then

  66. ' There might be more data, so store the data
    received so far.

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

  68. ' Check for end-of-file tag. If it is not there, read

  69. ' more data.

  70. content = state.sb.ToString()

  71. If content.IndexOf("") > -1 Then

  72. ' All the data has been read from the

  73. ' client. Display it on the console.

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

  75. ' Echo the data back to the client.

  76. Send(handler, content)

  77. Else

  78. ' Not all data received. Get more.

  79. handler.BeginReceive(state.buffer, 0, StateObject.
    BufferSize, 0, New AsyncCallback(AddressOf
    ReadCallback), state)

  80. End If

  81. End If

  82. End Sub 'ReadCallback

  83. Private Shared Sub Send(ByVal handler As Socket,
    ByVal data As String)

  84. ' Convert the string data to byte data using
    ASCII encoding.

  85. Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)

  86. ' Begin sending the data to the remote device.

  87. handler.BeginSend(byteData, 0, byteData.Length, 0,
    New AsyncCallback(AddressOf SendCallback), handler)

  88. End Sub 'Send

  89. Private Shared Sub SendCallback(ByVal ar As IAsyncResult)

  90. ' Retrieve the socket from the state object.

  91. Dim handler As Socket = CType(ar.AsyncState, Socket)

  92. ' Complete sending the data to the remote device.

  93. Dim bytesSent As Integer = handler.EndSend(ar)

  94. Console.WriteLine("Sent {0} bytes to client.", bytesSent)

  95. handler.Shutdown(SocketShutdown.Both)

  96. handler.Close()

  97. ' Signal the main thread to continue.

  98. allDone.Set()

  99. End Sub 'SendCallback

  100. End Class 'AsynchronousSocketListener

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

编程 单片机 应用 方面 篇文章 学习 通信 代码 例子 完了 方式 智能 智能家居 更多 服务器 状态 知识 程序 网卡 芯片 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 数据库索引性别男女 政府应急软件开发 各种软件数据库 河南的dns服务器虚拟主机 恒丰银行软件开发面试 一体化机柜服务器 塔科夫一直服务器连接失败 中国互联网第一股网盛科技 护苗网络安全课的儿童画 交换机是不是网络安全设备 如何统计数据库两个表中相同数据 软件开发公司app开发 服务直销软件开发 数据库技术的问题 mc服务器地图获取 学生成绩管理系统数据库字段 服务器连接速度是什么意思 期刊被数据库收录情况一般多少 如何删除数据库表中多行记录 中小企业数据库架构 交换机是不是网络安全设备 知网如何使用博士论文数据库 数据库标识列录入数据 龙之谷南方电信大区服务器名称 网络安全渗透题目在线 广元跑腿app软件开发 泰拉瑞亚软核服务器ip地址 地籍数据的属性数据库 2013年1月软件开发工具 网络安全宣传标语28字
0