一个基于VB.net的异步Socket网络TCP通信可防止任意一端意外终止TCP连接的类,。

来源:互联网 发布:美国10月大非农数据 编辑:程序博客网 时间:2024/05/16 02:30

之前,因为要做一个TCP通信的项目,有研究一下Socket类,但是为了快速完成任务,还是在网上找了一些源码来调试测试,发现很多源码都无法触发TCP连接的任意一端

的突然意外中断连接的事件,于是本人基于他人的源码基础上进行了修改,可以触发这一事件,可使TCP连接的另一端触发对方已经终止TCP连接事件。

以下,奉上本人修改后的源码类:

1)TCP 服务器TCP 侦听类。

[vb] view plaincopyprint?
  1. Imports System.Net  
  2. Imports System.Net.Sockets  
  3. Imports System.Threading  
  4. Imports System.Text  
  5.   
  6.   
  7. '**********************************************************************************************************  
  8. '''''' 类名:TCPServer     
  9. '''''' 说明:监听主线程,用于监听客户端联接,并记录客户端联接,接收和发送数据   
  10. '''''' 与客户端的联接采用TCP联接   
  11. '**********************************************************************************************************  
  12.   
  13.   
  14. ''' <summary>   
  15. ''' 侦听客户端联接   
  16. ''' </summary>   
  17. Public Class TCPServer 
  18.  
  19. #Region "私有成员"   
  20.     Private _LocationListenSocket As Socket '本地侦听服务  
  21.     Private _ListenPort As String '服务器侦听客户端联接的端口  
  22.     Private _MaxClient As Integer '最大客户端连接数  
  23.     Private _Clients As New SortedList '客户端队列  
  24.     Private _ListenThread As Thread = Nothing '侦听线程  
  25.     Private _ServerStart As Boolean = False '服务器是否已经启动  
  26.     Private _RecvMax As Integer '接收缓冲区大小  
  27. #End Region  
  28.  
  29. #Region "事件"   
  30.     ''' <summary>   
  31.     ''' 客户端联接事件   
  32.     ''' </summary>   
  33.     ''' <param name="IP">客户端联接IP</param>   
  34.     ''' <param name="Port">客户端联接端口号</param>   
  35.     ''' <remarks></remarks>   
  36.     Public Event ClientConnected(ByVal IP As StringByVal Port As String)  
  37.     ''' <summary>   
  38.     ''' 客户端断开事件   
  39.     ''' </summary>   
  40.     ''' <param name="IP">客户端联接IP</param>   
  41.     ''' <param name="Port">客户端联接端口号</param>  
  42.     ''' <remarks></remarks>   
  43.     Public Event ClientClose(ByVal IP As StringByVal Port As String)  
  44.     ''' <summary>   
  45.     ''' 接收到客户端的数据   
  46.     ''' </summary>   
  47.     ''' <param name="value">数据</param>   
  48.     ''' <param name="IPAddress">数据来源IP</param>   
  49.     ''' <param name="Port">数据来源端口</param>   
  50.     ''' <remarks></remarks>   
  51.     Public Event DataArrived(ByVal value As Byte(), ByVal Len As IntegerByVal IPAddress As StringByVal Port As String)  
  52.     ''' <summary>   
  53.     ''' 异常数据   
  54.     ''' </summary>   
  55.     ''' <param name="ex"></param>   
  56.     ''' <remarks></remarks>   
  57.     Public Event Exception(ByVal ex As Exception) 
  58.  
  59. #End Region  
  60.  
  61. #Region "属性"   
  62.     ''' <summary>   
  63.     ''' 侦听服务是否已经启动   
  64.     ''' </summary>   
  65.     ''' <value></value>   
  66.     ''' <returns></returns>   
  67.     ''' <remarks></remarks>   
  68.     Public ReadOnly Property IsServerStart() As Boolean  
  69.         Get  
  70.             Return _ServerStart  
  71.         End Get  
  72.     End Property 
  73. #End Region  
  74.  
  75. #Region "方法"   
  76.     ''' <summary>   
  77.     ''' 实例 TCPServer   
  78.     ''' </summary>   
  79.     ''' <param name="Port">侦听客户端联接的端口号</param>  
  80.     ''' <param name="MaxClient">最大可以联接的客户端数量</param>   
  81.     ''' <param name="RecvMax">接收缓冲区大小</param>  
  82.     ''' <param name="RecvSleep">接收线程睡眠时间</param>   
  83.     ''' <remarks></remarks>   
  84.     Sub New(ByVal Port As StringByVal MaxClient As IntegerByVal RecvMax As IntegerByVal RecvSleep As Integer)  
  85.         Try  
  86.             Dim strHostName As String = Dns.GetHostName()  
  87.             _ListenPort = Port  
  88.             _MaxClient = MaxClient  
  89.             _RecvMax = RecvMax  
  90.             Dim strServerHost As New IPEndPoint(IPAddress.Any, Int32.Parse(_ListenPort))  
  91.             '建立TCP侦听   
  92.             _LocationListenSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)  
  93.             _LocationListenSocket.Bind(strServerHost)  
  94.             _LocationListenSocket.Listen(_MaxClient)  
  95.             _LocationListenSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.AcceptConnection, 1)  
  96.         Catch ex As Exception  
  97.             RaiseEvent Exception(ex)  
  98.         End Try  
  99.     End Sub  
  100.   
  101.     ''' <summary>   
  102.     ''' 开始侦听服务   
  103.     ''' </summary>   
  104.     ''' <remarks></remarks>   
  105.     Public Sub StartServer()  
  106.         _ServerStart = True  
  107.         Try  
  108.             _ListenThread = New Thread(New ThreadStart(AddressOf ListenClient))  
  109.             _ListenThread.Name = "监听客户端主线程"  
  110.             _ListenThread.Start()  
  111.         Catch ex As Exception  
  112.             If (Not _LocationListenSocket Is NothingThen  
  113.                 If _LocationListenSocket.Connected Then  
  114.                     _LocationListenSocket.Close()  
  115.                 End If  
  116.             End If  
  117.             RaiseEvent Exception(ex)  
  118.         End Try  
  119.     End Sub  
  120.   
  121.     ''' <summary>   
  122.     ''' 关闭侦听   
  123.     ''' </summary>   
  124.     ''' <remarks></remarks>   
  125.     Public Sub Close()  
  126.         Try  
  127.             _ServerStart = False  
  128.             'CloseAllClient()   
  129.             Thread.Sleep(5)  
  130.             _ListenThread.Abort()  
  131.             _LocationListenSocket.Close()  
  132.             _ListenThread = Nothing  
  133.         Catch ex As Exception  
  134.             RaiseEvent Exception(ex)  
  135.         End Try  
  136.     End Sub  
  137.   
  138.     ''' <summary>   
  139.     ''' 客户端侦听线程   
  140.     ''' </summary>   
  141.     ''' <remarks></remarks>   
  142.     Private Sub ListenClient()  
  143.         Dim sKey As String  
  144.         While (_ServerStart)  
  145.             Try  
  146.                 If Not _LocationListenSocket Is Nothing Then  
  147.                     Dim clientSocket As System.Net.Sockets.Socket  
  148.                     clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)  
  149.                     clientSocket = _LocationListenSocket.Accept()  
  150.                     If Not clientSocket Is Nothing Then  
  151.                         Dim clientInfoT As IPEndPoint = CType(clientSocket.RemoteEndPoint, IPEndPoint)  
  152.                         sKey = clientInfoT.Address.ToString & "\&" & clientInfoT.Port.ToString  
  153.                         _Clients.Add(sKey, clientSocket)  
  154.                         RaiseEvent ClientConnected(clientInfoT.Address.ToString, clientInfoT.Port.ToString) '举起有客户端联接的事件  
  155.                         '启动客户端接收主线程,开始侦听并接收客户端上传的数据  
  156.                         Dim lb As New ClientCommunication(_LocationListenSocket, clientSocket, Me)  
  157.                         AddHandler lb.Exception, AddressOf WriteErrorEvent_ClientCommunication  
  158.                         Dim thrClient As New Thread(New ThreadStart(AddressOf lb.serverThreadProc))  
  159.                         thrClient.Name = "客户端接收线程,客户端" & clientInfoT.Address.ToString & ":" & clientInfoT.Port.ToString  
  160.                         thrClient.Start()  
  161.                     End If  
  162.                 End If  
  163.             Catch ex As Exception  
  164.                 RaiseEvent Exception(ex)  
  165.             End Try  
  166.         End While  
  167.     End Sub  
  168.   
  169.     Private Sub WriteErrorEvent_ClientCommunication(ByVal ex As Exception)  
  170.         RaiseEvent Exception(ex)  
  171.     End Sub  
  172.   
  173.     Public Sub CloseClient(ByVal IP As StringByVal Port As String)  
  174.         GetClientSocket(IP, Port).Close()  
  175.         GetClientClose(IP, Port)  
  176.     End Sub  
  177.     'Public Sub AlertNoticeClientAll(ByVal DepartmentName As String, ByVal LineName As String, ByVal ErrorCode As Integer)  
  178.     '    '#DepartmentName,LineName,AlertCodeValue.   
  179.     '    ' ''Dim mStr As String   
  180.     '    ' ''mStr = "#" & DepartmentName & "," & LineName & "," & ErrorCode  
  181.     '    ' ''Dim SendByte() As Byte = System.Text.UTF8Encoding.Default.GetBytes(mStr)  
  182.     '    ' ''For Each sc As System.Net.Sockets.Socket In _ClientComputers.Values  
  183.     '    ' ''    sc.Send(SendByte, SendByte.Length(), SocketFlags.None)  
  184.     '    ' ''Next   
  185.     'End Sub   
  186.     Public Sub CloseAllClient()  
  187.         For Each sc As System.Net.Sockets.Socket In _Clients.Values  
  188.             '断开所有工作站的Socket连接。   
  189.             Dim clientInfoT As IPEndPoint = CType(sc.RemoteEndPoint, IPEndPoint)  
  190.             CloseClient(clientInfoT.Address.ToString, clientInfoT.Port.ToString)  
  191.         Next  
  192.     End Sub 
  193. #Region "接收客户端的数据"   
  194.   
  195.     ''' <summary>   
  196.     ''' 接收到客户端的数据-字节数组   
  197.     ''' </summary>   
  198.     ''' <param name="value">数据内容</param>   
  199.     ''' <param name="Len">字节长度</param>   
  200.     ''' <param name="IPAddress">发送该数据的IP地址</param>   
  201.     ''' <param name="Port">发送该数据的端口号</param>  
  202.     ''' <remarks></remarks>   
  203.     Private Sub GetData_Byte(ByVal value As Byte(), ByVal Len As IntegerByVal IPAddress As StringByVal Port As String)  
  204.         Try  
  205.             RaiseEvent DataArrived(value, Len, IPAddress, Port)  
  206.             'Catch exx As Sockets.SocketException   
  207.             '    CloseClient(IPAddress, Port)  
  208.         Catch ex As Exception  
  209.             RaiseEvent Exception(ex)  
  210.         End Try  
  211.     End Sub  
  212.   
  213.     ''' <summary>   
  214.     ''' 得到客户端断开或失去客户端联连事件   
  215.     ''' </summary>   
  216.     ''' <param name="IP">客户端联接IP</param>   
  217.     ''' <param name="Port">客户端联接端口号</param>  
  218.     ''' <remarks></remarks>   
  219.     Private Sub GetClientClose(ByVal IP As StringByVal Port As String)  
  220.         Try  
  221.             If _Clients.ContainsKey(IP & "\&" & Port) Then  
  222.                 SyncLock _Clients.SyncRoot  
  223.                     '_Clients.Item(IP & "\&" & Port)  
  224.                     _Clients.Remove(IP & "\&" & Port)  
  225.                 End SyncLock  
  226.             End If  
  227.             RaiseEvent ClientClose(IP, Port)  
  228.         Catch ex As Exception  
  229.             RaiseEvent Exception(ex)  
  230.         End Try  
  231.     End Sub 
  232. #End Region  
  233.  
  234.  
  235. #Region "向客户端发送数据"   
  236.   
  237.     ''' <summary>   
  238.     ''' 向客户端发送信息   
  239.     ''' </summary>   
  240.     ''' <param name="value">发送的内容</param>   
  241.     ''' <param name="IPAddress">IP地址</param>  
  242.     ''' <param name="Port">端口号</param>   
  243.     ''' <returns> Boolean</returns>   
  244.     ''' <remarks></remarks>   
  245.     Public Function SendData(ByVal value As Byte(), ByVal IPAddress As StringByVal Port As StringAs Boolean  
  246.         Try  
  247.             Dim clientSocket As System.Net.Sockets.Socket  
  248.             clientSocket = _Clients.Item(IPAddress & "\&" & Port)  
  249.             clientSocket.Send(value, value.Length, SocketFlags.None)  
  250.             Return True  
  251.         Catch ex As Exception  
  252.             RaiseEvent Exception(ex)  
  253.             Return False  
  254.         End Try  
  255.     End Function  
  256.     Public Function SendFile(ByVal value As StringByVal IPAddress As StringByVal Port As StringAs Boolean  
  257.         Try  
  258.             Dim clientSocket As System.Net.Sockets.Socket  
  259.             clientSocket = _Clients.Item(IPAddress & "\&" & Port)  
  260.             clientSocket.SendFile(value)  
  261.             Return True  
  262.         Catch ex As Exception  
  263.             RaiseEvent Exception(ex)  
  264.             Return False  
  265.         End Try  
  266.     End Function  
  267.     Public Function SendDataToAllClient(ByVal value As Byte()) As Boolean  
  268.         Try  
  269.             For Each clientSocket As System.Net.Sockets.Socket In _Clients.Values  
  270.                 clientSocket.Send(value, value.Length, SocketFlags.None)  
  271.             Next  
  272.             Return True  
  273.         Catch ex As Exception  
  274.             RaiseEvent Exception(ex)  
  275.             Return False  
  276.         End Try  
  277.     End Function 
  278.  
  279. #End Region   
  280.   
  281.     ''' <summary>   
  282.     ''' 得到客户端的Socket联接   
  283.     ''' </summary>   
  284.     ''' <param name="IPAddress">客户端的IP</param>   
  285.     ''' <param name="Port">客户端的端口号</param>   
  286.     ''' <returns>Socket联接</returns>   
  287.     ''' <remarks></remarks>   
  288.     Private Function GetClientSocket(ByVal IPAddress As StringByVal Port As StringAs Socket  
  289.         Try  
  290.             Dim ClientSocket As Socket  
  291.             ClientSocket = _Clients.Item(IPAddress & "\&" & Port)  
  292.             Return ClientSocket  
  293.         Catch ex As Exception  
  294.             RaiseEvent Exception(ex)  
  295.             Return Nothing  
  296.         End Try  
  297.     End Function 
  298. #End Region   
  299.   
  300.     Private Class ClientCommunication  
  301.         Public Event Exception(ByVal ex As Exception)  
  302.   
  303.         Private ServerSocket As New System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)  
  304.         Private myClientSocket As New System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)  
  305.         Private myParentObject As TCPServer  
  306.         Private oldbytes() As Byte  
  307.         Private _IPAddress, _Port As String  
  308.         Private NclientInfoT As IPEndPoint = Nothing  
  309.         Private iLen As Integer  
  310.         Private allDone As New ManualResetEvent(False)  
  311.         ''' <summary>   
  312.         ''' 实例ClientCommunication类   
  313.         ''' </summary>   
  314.         ''' <param name="ServerSocket"></param>   
  315.         ''' <param name="ClientSocket"></param>  
  316.         ''' <param name="ParentObject"></param>   
  317.         ''' <remarks></remarks>   
  318.         Public Sub New(ByVal ServerSocket As Socket, ByVal ClientSocket As Socket, ByVal ParentObject As TCPServer)  
  319.             Me.ServerSocket = ServerSocket  
  320.             myClientSocket = ClientSocket  
  321.             myParentObject = ParentObject  
  322.             NclientInfoT = CType(myClientSocket.RemoteEndPoint, IPEndPoint)  
  323.             _IPAddress = NclientInfoT.Address.ToString  
  324.             _Port = NclientInfoT.Port.ToString  
  325.         End Sub  
  326.   
  327.         ''' <summary>   
  328.         ''' 客户端通讯主线程   
  329.         ''' </summary>   
  330.         ''' <remarks></remarks>   
  331.         Public Sub serverThreadProc()  
  332.             Try  
  333.                 Dim sb As New SocketAndBuffer  
  334.                 sb.Socket = myClientSocket  
  335.                 sb.Socket.BeginReceive(sb.Buffer, 0, sb.Buffer.Length, SocketFlags.None, AddressOf ReceiveCallBack, sb)  
  336.                 'allDone.WaitOne()   
  337.             Catch ex As Exception  
  338.                 RaiseEvent Exception(ex)  
  339.             End Try  
  340.         End Sub  
  341.   
  342.         ''' <summary>   
  343.         ''' socket异步接收回调函数   
  344.         ''' </summary>   
  345.         ''' <param name="ar"></param>   
  346.         ''' <remarks></remarks>   
  347.         Private Sub ReceiveCallBack(ByVal ar As IAsyncResult)  
  348.             Dim sb As SocketAndBuffer  
  349.             allDone.Set()  
  350.             sb = CType(ar.AsyncState, SocketAndBuffer)  
  351.             Try  
  352.                 If sb.Socket.Connected Then  
  353.                     iLen = sb.Socket.EndReceive(ar)  
  354.                     If iLen > 0 Then  
  355.                         ReDim oldbytes(iLen - 1)  
  356.                         Array.Copy(sb.Buffer, 0, oldbytes, 0, iLen)  
  357.                         myParentObject.GetData_Byte(oldbytes, oldbytes.Length, _IPAddress, _Port)  
  358.                         sb.Socket.BeginReceive(sb.Buffer, 0, sb.Buffer.Length, SocketFlags.None, AddressOf ReceiveCallBack, sb)  
  359.                     Else  
  360.                         If (Not myClientSocket Is NothingThen  
  361.                             If myClientSocket.Connected Then  
  362.                                 myClientSocket.Close()  
  363.                             Else  
  364.                                 myClientSocket.Close()  
  365.                             End If  
  366.                             myClientSocket = Nothing  
  367.                             If Not NclientInfoT Is Nothing Then  
  368.                                 myParentObject._Clients.Remove(_IPAddress & "\&" & _Port)  
  369.                                 myParentObject.GetClientClose(_IPAddress, _Port)  
  370.                             End If  
  371.                         End If  
  372.                     End If  
  373.                 End If  
  374.             Catch ex As Exception  
  375.                 If (Not myClientSocket Is NothingThen  
  376.                     If myClientSocket.Connected Then  
  377.                         myClientSocket.Close()  
  378.                     Else  
  379.                         myClientSocket.Close()  
  380.                     End If  
  381.                     myClientSocket = Nothing  
  382.                     If Not NclientInfoT Is Nothing Then  
  383.                         myParentObject._Clients.Remove(_IPAddress & "\&" & _Port)  
  384.                         myParentObject.GetClientClose(_IPAddress, _Port)  
  385.                     End If  
  386.                 End If  
  387.                 RaiseEvent Exception(ex)  
  388.             End Try  
  389.         End Sub  
  390.   
  391.         ''' <summary>   
  392.         ''' 异步操作socket缓冲类   
  393.         ''' </summary>   
  394.         ''' <remarks></remarks>   
  395.         Private Class SocketAndBuffer  
  396.             Public Socket As System.Net.Sockets.Socket  
  397.             Public Buffer(8192) As Byte  
  398.         End Class  
  399.     End Class  
  400.   
  401.   
  402. End Class  


2)TCP 客户端连接通信类

[vb] view plaincopyprint?
  1. Imports System.Net  
  2. Imports System.Net.Sockets  
  3. Imports System.Threading  
  4.   
  5. Public Class TCPClient 
  6. #Region "私有成员"   
  7.     Private _LocationClientSocket As Socket '本地侦听服务  
  8.     Private _LocalPort As String '本地端口  
  9.     Private _LocalHostName As String  
  10.     Private _LocalIP As String  
  11.     Private autoEvent As AutoResetEvent  
  12.     Private _RemoteHostName As String '遠程端計算機名  
  13.     Private _RemoteIP As String     '遠程端計算機IP  
  14.     Private _RemotePort As String   '遠程端計算機Port  
  15.     Private _RemoteIPOrHostName As String  
  16.     'Private _MaxClient As Integer '最大客户端连接数   
  17.     'Private _Clients As New SortedList '客户端队列  
  18.     'Private _ListenThread As Thread = Nothing '侦听线程   
  19.     'Private _ServerStart As Boolean = False '服务器是否已经启动  
  20.     Private _RecvMax As Integer '接收缓冲区大小   
  21.   
  22.     Private ClientThread As Thread  
  23.     'Private ClitenStream As NetworkStream   
  24.     Private IsStop As Boolean = False 
  25.  
  26. #End Region  
  27.  
  28. #Region "事件"   
  29.     ''' <summary>   
  30.     ''' 客户端联接事件   
  31.     ''' </summary>    
  32.     ''' <remarks></remarks>   
  33.     Public Event ClientConnected()  
  34.     ''' <summary>   
  35.     ''' 客户端断开事件   
  36.     ''' </summary>   
  37.     ''' <remarks></remarks>   
  38.     Public Event ClientClosed()  
  39.     ''' <summary>   
  40.     ''' 接收到客户端的数据   
  41.     ''' </summary>   
  42.     ''' <param name="value">数据</param>   
  43.     ''' <remarks></remarks>   
  44.     Public Event DataArrived(ByVal value As Byte(), ByVal Len As Integer)  
  45.     ''' <summary>   
  46.     ''' 异常数据   
  47.     ''' </summary>   
  48.     ''' <param name="ex"></param>   
  49.     ''' <remarks></remarks>   
  50.     Public Event Exception(ByVal ex As Exception) 
  51. #End Region  
  52.  
  53. #Region "属性"   
  54.     ''' <summary>   
  55.     ''' 是否已經連接   
  56.     ''' </summary>   
  57.     ''' <value></value>   
  58.     ''' <returns></returns>   
  59.     ''' <remarks></remarks>   
  60.     Public ReadOnly Property Connected() As Boolean  
  61.         Get  
  62.             Return _LocationClientSocket.Connected  
  63.         End Get  
  64.     End Property  
  65.   
  66.     ''' <summary>   
  67.     ''' 本地計算機名稱   
  68.     ''' </summary>   
  69.     ''' <value></value>   
  70.     ''' <returns></returns>   
  71.     ''' <remarks></remarks>   
  72.     Public ReadOnly Property LocalHostName() As String  
  73.         Get  
  74.             Return _LocalHostName  
  75.         End Get  
  76.     End Property  
  77.   
  78.     ''' <summary>   
  79.     ''' 本地計算IP   
  80.     ''' </summary>   
  81.     ''' <value></value>   
  82.     ''' <returns></returns>   
  83.     ''' <remarks></remarks>   
  84.     Public ReadOnly Property LocalIP() As String  
  85.         Get  
  86.             Return _LocalIP  
  87.         End Get  
  88.     End Property  
  89.   
  90.     ''' <summary>   
  91.     ''' 本地計算機端口   
  92.     ''' </summary>   
  93.     ''' <value></value>   
  94.     ''' <returns></returns>   
  95.     ''' <remarks></remarks>   
  96.     Public ReadOnly Property LocalPort() As String  
  97.         Get  
  98.             Return _LocalPort  
  99.         End Get  
  100.     End Property  
  101.   
  102.     ''' <summary>   
  103.     ''' 遠程計算機IP   
  104.     ''' </summary>   
  105.     ''' <value></value>   
  106.     ''' <returns></returns>   
  107.     ''' <remarks></remarks>   
  108.     Public ReadOnly Property RemoteIP() As String  
  109.         Get  
  110.             Return _RemoteIP  
  111.         End Get  
  112.   
  113.     End Property  
  114.   
  115.     ''' <summary>   
  116.     ''' 遠程計算機端口   
  117.     ''' </summary>   
  118.     ''' <value></value>   
  119.     ''' <returns></returns>   
  120.     ''' <remarks></remarks>   
  121.     Public ReadOnly Property RemotePort() As String  
  122.         Get  
  123.             Return _RemotePort  
  124.         End Get  
  125.   
  126.     End Property  
  127.   
  128.     ''' <summary>   
  129.     ''' 遠程計算機名稱   
  130.     ''' </summary>   
  131.     ''' <value></value>   
  132.     ''' <returns></returns>   
  133.     ''' <remarks></remarks>   
  134.     Public ReadOnly Property RemoteHostName() As String  
  135.         Get  
  136.             Return _RemoteHostName  
  137.         End Get  
  138.   
  139.     End Property 
  140. #End Region  
  141.  
  142. #Region "方法"   
  143.     ''' <summary>   
  144.     ''' 实例 TCPServer   
  145.     ''' </summary>   
  146.     ''' <param name="RemoteIPOrHostName">需要連接服務的IP地址或計算機名稱</param>  
  147.     ''' <param name="Port">侦听客户端联接的端口号</param>  
  148.     ''' <param name="RecvMax">接收缓冲区大小</param>   
  149.     ''' <param name="RecvSleep">接收线程睡眠时间</param>  
  150.     ''' <remarks></remarks>   
  151.     Sub New(ByVal RemoteIPOrHostName As StringByVal Port As StringByVal RecvMax As IntegerByVal RecvSleep As Integer)  
  152.         Try  
  153.             _LocalHostName = Dns.GetHostName()  
  154.   
  155.             '_RemoteIP = Dns.GetHostAddresses(RemoteIPOrHostName)(0).ToString  
  156.             _RemotePort = Port  
  157.             _RecvMax = RecvMax  
  158.             _RemoteIPOrHostName = RemoteIPOrHostName  
  159.             _RemotePort = Port  
  160.             'Dim strServerHost As New IPEndPoint(IPAddress.Any, Int32.Parse(_ListenPort))  
  161.   
  162.             '建立TCP侦听   
  163.             _LocationClientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)  
  164.             autoEvent = New AutoResetEvent(False)  
  165.             Dim cThread As New Thread(New ThreadStart(AddressOf ConnectHost))  
  166.             cThread.Start()  
  167.             autoEvent.WaitOne(1000, False)  
  168.             cThread.Abort()  
  169.         Catch ex As Exception  
  170.             RaiseEvent Exception(ex)  
  171.         End Try  
  172.     End Sub  
  173.     Public Sub ConnectHost()  
  174.         Try  
  175.             Dim remoteIP As Net.IPAddress = Nothing  
  176.             If IPAddress.TryParse(_RemoteIPOrHostName, remoteIP) Then  
  177.                 '_LocationClientSocket.BeginConnect()  
  178.                 _LocationClientSocket.Connect(remoteIP, _RemotePort)  
  179.                 '_RemoteIP = RemoteHostName  
  180.   
  181.             Else  
  182.                 _LocationClientSocket.Connect(_RemoteIPOrHostName, _RemotePort)  
  183.                 _RemoteHostName = RemoteHostName  
  184.             End If  
  185.   
  186.             If _LocationClientSocket.Connected Then  
  187.                 _LocationClientSocket.SendBufferSize = _RecvMax  
  188.                 _LocationClientSocket.ReceiveBufferSize = _RecvMax  
  189.   
  190.                 Dim clientInfoT As IPEndPoint  
  191.   
  192.                 clientInfoT = CType(_LocationClientSocket.RemoteEndPoint, IPEndPoint)  
  193.                 _RemoteIP = clientInfoT.Address.ToString  
  194.                 'Dim remoteHost As Net.IPHostEntry   
  195.   
  196.                 _RemoteHostName = Dns.GetHostEntry(_RemoteIP).HostName  
  197.   
  198.                 clientInfoT = CType(_LocationClientSocket.LocalEndPoint, IPEndPoint)  
  199.   
  200.                 _LocalIP = clientInfoT.Address.ToString  
  201.                 _LocalPort = clientInfoT.Port.ToString  
  202.   
  203.                 IsStop = False  
  204.   
  205.                 RaiseEvent ClientConnected()  
  206.   
  207.                 ClientThread = New Thread(New ThreadStart(AddressOf ClientListen))  
  208.                 ClientThread.Start()  
  209.                 autoEvent.Set()  
  210.             End If  
  211.         Catch ex As Exception  
  212.   
  213.         End Try  
  214.   
  215.   
  216.     End Sub  
  217.   
  218.     ''' <summary>   
  219.     ''' 關閉客戶端連接   
  220.     ''' </summary>   
  221.     ''' <remarks></remarks>   
  222.     Public Sub Close()  
  223.         Try  
  224.             If _LocationClientSocket Is Nothing Then Exit Sub  
  225.             IsStop = True  
  226.             If Not ClientThread Is Nothing Then  
  227.                 Thread.Sleep(5)  
  228.                 ClientThread.Abort()  
  229.             End If  
  230.             _LocationClientSocket.Close()  
  231.             _LocationClientSocket = Nothing  
  232.             ClientThread = Nothing  
  233.             RaiseEvent ClientClosed()  
  234.         Catch ex As Exception  
  235.             RaiseEvent Exception(ex)  
  236.         End Try  
  237.   
  238.     End Sub  
  239.   
  240.     ''' <summary>   
  241.     ''' 实例 TCPServer   
  242.     ''' </summary>   
  243.     ''' <param name="value">發送的資料,二進制數組</param>  
  244.     ''' <remarks></remarks>   
  245.     Public Function SendData(ByVal value As Byte()) As Boolean  
  246.         Try  
  247.             _LocationClientSocket.Send(value)  
  248.         Catch ex As Exception  
  249.             RaiseEvent Exception(ex)  
  250.         End Try  
  251.     End Function  
  252.   
  253.     Private Sub ClientListen()  
  254.         Dim tmpByt(8192) As Byte  
  255.         Dim recData() As Byte  
  256.         Dim R As Integer  
  257.         While Not IsStop  
  258.             Try  
  259.                 If _LocationClientSocket.Poll(50, SelectMode.SelectWrite) Then  
  260.                     R = _LocationClientSocket.Receive(tmpByt)  
  261.                     If R > 0 Then  
  262.                         ReDim recData(R - 1)  
  263.                         Array.Copy(tmpByt, recData, R)  
  264.                         RaiseEvent DataArrived(recData, recData.Length)  
  265.                     Else  
  266.                         If (Not _LocationClientSocket Is NothingThen  
  267.                             _LocationClientSocket.Close()  
  268.                             _LocationClientSocket = Nothing  
  269.                             IsStop = True  
  270.                             RaiseEvent ClientClosed()  
  271.                         End If  
  272.                     End If  
  273.                 End If  
  274.             Catch sex As SocketException  
  275.                 If sex.ErrorCode = 10054 Then  
  276.                     If (Not _LocationClientSocket Is NothingThen  
  277.                         _LocationClientSocket.Close()  
  278.                         _LocationClientSocket = Nothing  
  279.                         IsStop = True  
  280.                         RaiseEvent ClientClosed()  
  281.                     End If  
  282.                 Else  
  283.                     RaiseEvent Exception(sex)  
  284.                 End If  
  285.             Catch ex As Exception  
  286.                 RaiseEvent Exception(ex)  
  287.             End Try  
  288.         End While  
  289.     End Sub 
  290. #End Region   
  291.   
  292. End Class  

窗体调用TCP 类如下

服务器端:

[vb] view plaincopyprint?
  1. Public WithEvents MyClient As TCPServer  

客户机端:

[vb] view plaincopyprint?
  1. Public WithEvents MyClient As TCPClient  

原创粉丝点击