之前,因为要做一个TCP通信的项目,有研究一下Socket类,但是为了快速完成任务,还是在网上找了一些源码来调试测试,发现很多源码都无法触发TCP连接的任意一端
的突然意外中断连接的事件,于是本人基于他人的源码基础上进行了修改,可以触发这一事件,可使TCP连接的另一端触发对方已经终止TCP连接事件。
原文链接:https://www.f2er.com/vb/258325.html以下,奉上本人修改后的源码类:
1)TCP 服务器TCP 侦听类。
- ImportsSystem.Net
- ImportsSystem.Net.Sockets
- ImportsSystem.Threading
- ImportsSystem.Text
- '**********************************************************************************************************
- ''''''类名:TCPServer
- ''''''说明:监听主线程,用于监听客户端联接,并记录客户端联接,接收和发送数据
- ''''''与客户端的联接采用TCP联接
- '**********************************************************************************************************
- '''<summary>
- '''侦听客户端联接
- '''</summary>
- PublicClassTCPServer
- #Region"私有成员"
- Private_LocationListenSocketAsSocket'本地侦听服务
- Private_ListenPortAsString'服务器侦听客户端联接的端口
- Private_MaxClientAsInteger'最大客户端连接数
- Private_ClientsAsNewSortedList'客户端队列
- Private_ListenThreadAsThread=Nothing'侦听线程
- Private_ServerStartAsBoolean=False'服务器是否已经启动
- Private_RecvMaxAsInteger'接收缓冲区大小
- #EndRegion
- #Region"事件"
- '''<summary>
- '''客户端联接事件
- '''</summary>
- '''<paramname="IP">客户端联接IP</param>
- '''<paramname="Port">客户端联接端口号</param>
- '''<remarks></remarks>
- PublicEventClientConnected(ByValIPAsString,ByValPortAsString)
- '''<summary>
- '''客户端断开事件
- '''</summary>
- '''<paramname="IP">客户端联接IP</param>
- '''<paramname="Port">客户端联接端口号</param>
- '''<remarks></remarks>
- PublicEventClientClose(ByValIPAsString,ByValPortAsString)
- '''<summary>
- '''接收到客户端的数据
- '''</summary>
- '''<paramname="value">数据</param>
- '''<paramname="IPAddress">数据来源IP</param>
- '''<paramname="Port">数据来源端口</param>
- '''<remarks></remarks>
- PublicEventDataArrived(ByValvalueAsByte(),ByValLenAsInteger,ByValIPAddressAsString,ByValPortAsString)
- '''<summary>
- '''异常数据
- '''</summary>
- '''<paramname="ex"></param>
- '''<remarks></remarks>
- PublicEventException(ByValexAsException)
- #EndRegion
- #Region"属性"
- '''<summary>
- '''侦听服务是否已经启动
- '''</summary>
- '''<value></value>
- '''<returns></returns>
- '''<remarks></remarks>
- PublicReadOnlyPropertyIsServerStart()AsBoolean
- Get
- Return_ServerStart
- EndGet
- EndProperty
- #EndRegion
- #Region"方法"
- '''<summary>
- '''实例 TCPServer
- '''</summary>
- '''<paramname="Port">侦听客户端联接的端口号</param>
- '''<paramname="MaxClient">最大可以联接的客户端数量</param>
- '''<paramname="RecvMax">接收缓冲区大小</param>
- '''<paramname="RecvSleep">接收线程睡眠时间</param>
- '''<remarks></remarks>
- SubNew(ByValPortAsString,ByValMaxClientAsInteger,ByValRecvMaxAsInteger,ByValRecvSleepAsInteger)
- Try
- DimstrHostNameAsString=Dns.GetHostName()
- _ListenPort=Port
- _MaxClient=MaxClient
- _RecvMax=RecvMax
- DimstrServerHostAsNewIPEndPoint(IPAddress.Any,Int32.Parse(_ListenPort))
- '建立TCP侦听
- _LocationListenSocket=NewSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp)
- _LocationListenSocket.Bind(strServerHost)
- _LocationListenSocket.Listen(_MaxClient)
- _LocationListenSocket.SetSocketOption(SocketOptionLevel.Tcp,SocketOptionName.AcceptConnection,1)
- CatchexAsException
- RaiseEventException(ex)
- EndTry
- EndSub
- '''<summary>
- '''开始侦听服务
- '''</summary>
- '''<remarks></remarks>
- PublicSubStartServer()
- _ServerStart=True
- Try
- _ListenThread=NewThread(NewThreadStart(AddressOfListenClient))
- _ListenThread.Name="监听客户端主线程"
- _ListenThread.Start()
- CatchexAsException
- If(Not_LocationListenSocketIsNothing)Then
- If_LocationListenSocket.ConnectedThen
- _LocationListenSocket.Close()
- EndIf
- EndIf
- RaiseEventException(ex)
- EndTry
- EndSub
- '''<summary>
- '''关闭侦听
- '''</summary>
- '''<remarks></remarks>
- PublicSubClose()
- Try
- _ServerStart=False
- 'CloseAllClient()
- Thread.Sleep(5)
- _ListenThread.Abort()
- _LocationListenSocket.Close()
- _ListenThread=Nothing
- CatchexAsException
- RaiseEventException(ex)
- EndTry
- EndSub
- '''<summary>
- '''客户端侦听线程
- '''</summary>
- '''<remarks></remarks>
- PrivateSubListenClient()
- DimsKeyAsString
- While(_ServerStart)
- Try
- IfNot_LocationListenSocketIsNothingThen
- DimclientSocketAsSystem.Net.Sockets.Socket
- clientSocket=NewSocket(AddressFamily.InterNetwork,ProtocolType.Tcp)
- clientSocket=_LocationListenSocket.Accept()
- IfNotclientSocketIsNothingThen
- DimclientInfoTAsIPEndPoint=CType(clientSocket.RemoteEndPoint,IPEndPoint)
- sKey=clientInfoT.Address.ToString&"\&"&clientInfoT.Port.ToString
- _Clients.Add(sKey,clientSocket)
- RaiseEventClientConnected(clientInfoT.Address.ToString,clientInfoT.Port.ToString)'举起有客户端联接的事件
- '启动客户端接收主线程,开始侦听并接收客户端上传的数据
- DimlbAsNewClientCommunication(_LocationListenSocket,clientSocket,Me)
- AddHandlerlb.Exception,AddressOfWriteErrorEvent_ClientCommunication
- DimthrClientAsNewThread(NewThreadStart(AddressOflb.serverThreadProc))
- thrClient.Name="客户端接收线程,客户端"&clientInfoT.Address.ToString&":"&clientInfoT.Port.ToString
- thrClient.Start()
- EndIf
- EndIf
- CatchexAsException
- RaiseEventException(ex)
- EndTry
- EndWhile
- EndSub
- PrivateSubWriteErrorEvent_ClientCommunication(ByValexAsException)
- RaiseEventException(ex)
- EndSub
- PublicSubCloseClient(ByValIPAsString,ByValPortAsString)
- GetClientSocket(IP,Port).Close()
- GetClientClose(IP,Port)
- EndSub
- 'PublicSubAlertNoticeClientAll(ByValDepartmentNameAsString,ByValLineNameAsString,ByValErrorCodeAsInteger)
- ''#DepartmentName,LineName,AlertCodeValue.
- ''''DimmStrAsString
- ''''mStr="#"&DepartmentName&","&LineName&","&ErrorCode
- ''''DimSendByte()AsByte=System.Text.UTF8Encoding.Default.GetBytes(mStr)
- ''''ForEachscAsSystem.Net.Sockets.SocketIn_ClientComputers.Values
- ''''sc.Send(SendByte,SendByte.Length(),SocketFlags.None)
- ''''Next
- 'EndSub
- PublicSubCloseAllClient()
- ForEachscAsSystem.Net.Sockets.SocketIn_Clients.Values
- '断开所有工作站的Socket连接。
- DimclientInfoTAsIPEndPoint=CType(sc.RemoteEndPoint,IPEndPoint)
- CloseClient(clientInfoT.Address.ToString,clientInfoT.Port.ToString)
- Next
- EndSub
- #Region"接收客户端的数据"
- '''<summary>
- '''接收到客户端的数据-字节数组
- '''</summary>
- '''<paramname="value">数据内容</param>
- '''<paramname="Len">字节长度</param>
- '''<paramname="IPAddress">发送该数据的IP地址</param>
- '''<paramname="Port">发送该数据的端口号</param>
- '''<remarks></remarks>
- PrivateSubGetData_Byte(ByValvalueAsByte(),ByValPortAsString)
- Try
- RaiseEventDataArrived(value,Len,IPAddress,Port)
- 'CatchexxAsSockets.SocketException
- 'CloseClient(IPAddress,Port)
- CatchexAsException
- RaiseEventException(ex)
- EndTry
- EndSub
- '''<summary>
- '''得到客户端断开或失去客户端联连事件
- '''</summary>
- '''<paramname="IP">客户端联接IP</param>
- '''<paramname="Port">客户端联接端口号</param>
- '''<remarks></remarks>
- PrivateSubGetClientClose(ByValIPAsString,ByValPortAsString)
- Try
- If_Clients.ContainsKey(IP&"\&"&Port)Then
- SyncLock_Clients.SyncRoot
- '_Clients.Item(IP&"\&"&Port)
- _Clients.Remove(IP&"\&"&Port)
- EndSyncLock
- EndIf
- RaiseEventClientClose(IP,Port)
- CatchexAsException
- RaiseEventException(ex)
- EndTry
- EndSub
- #EndRegion
- #Region"向客户端发送数据"
- '''<summary>
- '''向客户端发送信息
- '''</summary>
- '''<paramname="value">发送的内容</param>
- '''<paramname="IPAddress">IP地址</param>
- '''<paramname="Port">端口号</param>
- '''<returns>Boolean</returns>
- '''<remarks></remarks>
- PublicFunctionSendData(ByValvalueAsByte(),ByValPortAsString)AsBoolean
- Try
- DimclientSocketAsSystem.Net.Sockets.Socket
- clientSocket=_Clients.Item(IPAddress&"\&"&Port)
- clientSocket.Send(value,value.Length,SocketFlags.None)
- ReturnTrue
- CatchexAsException
- RaiseEventException(ex)
- ReturnFalse
- EndTry
- EndFunction
- PublicFunctionSendFile(ByValvalueAsString,ByValPortAsString)AsBoolean
- Try
- DimclientSocketAsSystem.Net.Sockets.Socket
- clientSocket=_Clients.Item(IPAddress&"\&"&Port)
- clientSocket.SendFile(value)
- ReturnTrue
- CatchexAsException
- RaiseEventException(ex)
- ReturnFalse
- EndTry
- EndFunction
- PublicFunctionSendDataToAllClient(ByValvalueAsByte())AsBoolean
- Try
- ForEachclientSocketAsSystem.Net.Sockets.SocketIn_Clients.Values
- clientSocket.Send(value,SocketFlags.None)
- Next
- ReturnTrue
- CatchexAsException
- RaiseEventException(ex)
- ReturnFalse
- EndTry
- EndFunction
- #EndRegion
- '''<summary>
- '''得到客户端的Socket联接
- '''</summary>
- '''<paramname="IPAddress">客户端的IP</param>
- '''<paramname="Port">客户端的端口号</param>
- '''<returns>Socket联接</returns>
- '''<remarks></remarks>
- PrivateFunctionGetClientSocket(ByValIPAddressAsString,ByValPortAsString)AsSocket
- Try
- DimClientSocketAsSocket
- ClientSocket=_Clients.Item(IPAddress&"\&"&Port)
- ReturnClientSocket
- CatchexAsException
- RaiseEventException(ex)
- ReturnNothing
- EndTry
- EndFunction
- #EndRegion
- PrivateClassClientCommunication
- PublicEventException(ByValexAsException)
- PrivateServerSocketAsNewSystem.Net.Sockets.Socket(AddressFamily.InterNetwork,ProtocolType.Tcp)
- PrivatemyClientSocketAsNewSystem.Net.Sockets.Socket(AddressFamily.InterNetwork,ProtocolType.Tcp)
- PrivatemyParentObjectAsTCPServer
- Privateoldbytes()AsByte
- Private_IPAddress,_PortAsString
- PrivateNclientInfoTAsIPEndPoint=Nothing
- PrivateiLenAsInteger
- PrivateallDoneAsNewManualResetEvent(False)
- '''<summary>
- '''实例ClientCommunication类
- '''</summary>
- '''<paramname="ServerSocket"></param>
- '''<paramname="ClientSocket"></param>
- '''<paramname="ParentObject"></param>
- '''<remarks></remarks>
- PublicSubNew(ByValServerSocketAsSocket,ByValClientSocketAsSocket,ByValParentObjectAsTCPServer)
- Me.ServerSocket=ServerSocket
- myClientSocket=ClientSocket
- myParentObject=ParentObject
- NclientInfoT=CType(myClientSocket.RemoteEndPoint,IPEndPoint)
- _IPAddress=NclientInfoT.Address.ToString
- _Port=NclientInfoT.Port.ToString
- EndSub
- '''<summary>
- '''客户端通讯主线程
- '''</summary>
- '''<remarks></remarks>
- PublicSubserverThreadProc()
- Try
- DimsbAsNewSocketAndBuffer
- sb.Socket=myClientSocket
- sb.Socket.BeginReceive(sb.Buffer,sb.Buffer.Length,SocketFlags.None,AddressOfReceiveCallBack,sb)
- 'allDone.WaitOne()
- CatchexAsException
- RaiseEventException(ex)
- EndTry
- EndSub
- '''<summary>
- '''socket异步接收回调函数
- '''</summary>
- '''<paramname="ar"></param>
- '''<remarks></remarks>
- PrivateSubReceiveCallBack(ByValarAsIAsyncResult)
- DimsbAsSocketAndBuffer
- allDone.Set()
- sb=CType(ar.AsyncState,SocketAndBuffer)
- Try
- Ifsb.Socket.ConnectedThen
- iLen=sb.Socket.EndReceive(ar)
- IfiLen>0Then
- ReDimoldbytes(iLen-1)
- Array.Copy(sb.Buffer,oldbytes,iLen)
- myParentObject.GetData_Byte(oldbytes,oldbytes.Length,_IPAddress,_Port)
- sb.Socket.BeginReceive(sb.Buffer,sb)
- Else
- If(NotmyClientSocketIsNothing)Then
- IfmyClientSocket.ConnectedThen
- myClientSocket.Close()
- Else
- myClientSocket.Close()
- EndIf
- myClientSocket=Nothing
- IfNotNclientInfoTIsNothingThen
- myParentObject._Clients.Remove(_IPAddress&"\&"&_Port)
- myParentObject.GetClientClose(_IPAddress,_Port)
- EndIf
- EndIf
- EndIf
- EndIf
- CatchexAsException
- If(NotmyClientSocketIsNothing)Then
- IfmyClientSocket.ConnectedThen
- myClientSocket.Close()
- Else
- myClientSocket.Close()
- EndIf
- myClientSocket=Nothing
- IfNotNclientInfoTIsNothingThen
- myParentObject._Clients.Remove(_IPAddress&"\&"&_Port)
- myParentObject.GetClientClose(_IPAddress,_Port)
- EndIf
- EndIf
- RaiseEventException(ex)
- EndTry
- EndSub
- '''<summary>
- '''异步操作socket缓冲类
- '''</summary>
- '''<remarks></remarks>
- PrivateClassSocketAndBuffer
- PublicSocketAsSystem.Net.Sockets.Socket
- PublicBuffer(8192)AsByte
- EndClass
- EndClass
- EndClass
Imports System.Net Imports System.Net.Sockets Imports System.Threading Imports System.Text '********************************************************************************************************** '''''' 类名:TCPServer '''''' 说明:监听主线程,用于监听客户端联接,并记录客户端联接,接收和发送数据 '''''' 与客户端的联接采用TCP联接 '********************************************************************************************************** ''' <summary> ''' 侦听客户端联接 ''' </summary> Public Class TCPServer #Region "私有成员" Private _LocationListenSocket As Socket '本地侦听服务 Private _ListenPort As String '服务器侦听客户端联接的端口 Private _MaxClient As Integer '最大客户端连接数 Private _Clients As New SortedList '客户端队列 Private _ListenThread As Thread = Nothing '侦听线程 Private _ServerStart As Boolean = False '服务器是否已经启动 Private _RecvMax As Integer '接收缓冲区大小 #End Region #Region "事件" ''' <summary> ''' 客户端联接事件 ''' </summary> ''' <param name="IP">客户端联接IP</param> ''' <param name="Port">客户端联接端口号</param> ''' <remarks></remarks> Public Event ClientConnected(ByVal IP As String,ByVal Port As String) ''' <summary> ''' 客户端断开事件 ''' </summary> ''' <param name="IP">客户端联接IP</param> ''' <param name="Port">客户端联接端口号</param> ''' <remarks></remarks> Public Event ClientClose(ByVal IP As String,ByVal Port As String) ''' <summary> ''' 接收到客户端的数据 ''' </summary> ''' <param name="value">数据</param> ''' <param name="IPAddress">数据来源IP</param> ''' <param name="Port">数据来源端口</param> ''' <remarks></remarks> Public Event DataArrived(ByVal value As Byte(),ByVal Len As Integer,ByVal IPAddress As String,ByVal Port As String) ''' <summary> ''' 异常数据 ''' </summary> ''' <param name="ex"></param> ''' <remarks></remarks> Public Event Exception(ByVal ex As Exception) #End Region #Region "属性" ''' <summary> ''' 侦听服务是否已经启动 ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property IsServerStart() As Boolean Get Return _ServerStart End Get End Property #End Region #Region "方法" ''' <summary> ''' 实例 TCPServer ''' </summary> ''' <param name="Port">侦听客户端联接的端口号</param> ''' <param name="MaxClient">最大可以联接的客户端数量</param> ''' <param name="RecvMax">接收缓冲区大小</param> ''' <param name="RecvSleep">接收线程睡眠时间</param> ''' <remarks></remarks> Sub New(ByVal Port As String,ByVal MaxClient As Integer,ByVal RecvMax As Integer,ByVal RecvSleep As Integer) Try Dim strHostName As String = Dns.GetHostName() _ListenPort = Port _MaxClient = MaxClient _RecvMax = RecvMax Dim strServerHost As New IPEndPoint(IPAddress.Any,Int32.Parse(_ListenPort)) '建立TCP侦听 _LocationListenSocket = New Socket(AddressFamily.InterNetwork,ProtocolType.Tcp) _LocationListenSocket.Bind(strServerHost) _LocationListenSocket.Listen(_MaxClient) _LocationListenSocket.SetSocketOption(SocketOptionLevel.Tcp,1) Catch ex As Exception RaiseEvent Exception(ex) End Try End Sub ''' <summary> ''' 开始侦听服务 ''' </summary> ''' <remarks></remarks> Public Sub StartServer() _ServerStart = True Try _ListenThread = New Thread(New ThreadStart(AddressOf ListenClient)) _ListenThread.Name = "监听客户端主线程" _ListenThread.Start() Catch ex As Exception If (Not _LocationListenSocket Is Nothing) Then If _LocationListenSocket.Connected Then _LocationListenSocket.Close() End If End If RaiseEvent Exception(ex) End Try End Sub ''' <summary> ''' 关闭侦听 ''' </summary> ''' <remarks></remarks> Public Sub Close() Try _ServerStart = False 'CloseAllClient() Thread.Sleep(5) _ListenThread.Abort() _LocationListenSocket.Close() _ListenThread = Nothing Catch ex As Exception RaiseEvent Exception(ex) End Try End Sub ''' <summary> ''' 客户端侦听线程 ''' </summary> ''' <remarks></remarks> Private Sub ListenClient() Dim sKey As String While (_ServerStart) Try If Not _LocationListenSocket Is Nothing Then Dim clientSocket As System.Net.Sockets.Socket clientSocket = New Socket(AddressFamily.InterNetwork,ProtocolType.Tcp) clientSocket = _LocationListenSocket.Accept() If Not clientSocket Is Nothing Then Dim clientInfoT As IPEndPoint = CType(clientSocket.RemoteEndPoint,IPEndPoint) sKey = clientInfoT.Address.ToString & "\&" & clientInfoT.Port.ToString _Clients.Add(sKey,clientSocket) RaiseEvent ClientConnected(clientInfoT.Address.ToString,clientInfoT.Port.ToString) '举起有客户端联接的事件 '启动客户端接收主线程,开始侦听并接收客户端上传的数据 Dim lb As New ClientCommunication(_LocationListenSocket,Me) AddHandler lb.Exception,AddressOf WriteErrorEvent_ClientCommunication Dim thrClient As New Thread(New ThreadStart(AddressOf lb.serverThreadProc)) thrClient.Name = "客户端接收线程,客户端" & clientInfoT.Address.ToString & ":" & clientInfoT.Port.ToString thrClient.Start() End If End If Catch ex As Exception RaiseEvent Exception(ex) End Try End While End Sub Private Sub WriteErrorEvent_ClientCommunication(ByVal ex As Exception) RaiseEvent Exception(ex) End Sub Public Sub CloseClient(ByVal IP As String,ByVal Port As String) GetClientSocket(IP,Port).Close() GetClientClose(IP,Port) End Sub 'Public Sub AlertNoticeClientAll(ByVal DepartmentName As String,ByVal LineName As String,ByVal ErrorCode As Integer) ' '#DepartmentName,AlertCodeValue. ' ' ''Dim mStr As String ' ' ''mStr = "#" & DepartmentName & "," & LineName & "," & ErrorCode ' ' ''Dim SendByte() As Byte = System.Text.UTF8Encoding.Default.GetBytes(mStr) ' ' ''For Each sc As System.Net.Sockets.Socket In _ClientComputers.Values ' ' '' sc.Send(SendByte,SocketFlags.None) ' ' ''Next 'End Sub Public Sub CloseAllClient() For Each sc As System.Net.Sockets.Socket In _Clients.Values '断开所有工作站的Socket连接。 Dim clientInfoT As IPEndPoint = CType(sc.RemoteEndPoint,IPEndPoint) CloseClient(clientInfoT.Address.ToString,clientInfoT.Port.ToString) Next End Sub #Region "接收客户端的数据" ''' <summary> ''' 接收到客户端的数据-字节数组 ''' </summary> ''' <param name="value">数据内容</param> ''' <param name="Len">字节长度</param> ''' <param name="IPAddress">发送该数据的IP地址</param> ''' <param name="Port">发送该数据的端口号</param> ''' <remarks></remarks> Private Sub GetData_Byte(ByVal value As Byte(),ByVal Port As String) Try RaiseEvent DataArrived(value,Port) 'Catch exx As Sockets.SocketException ' CloseClient(IPAddress,Port) Catch ex As Exception RaiseEvent Exception(ex) End Try End Sub ''' <summary> ''' 得到客户端断开或失去客户端联连事件 ''' </summary> ''' <param name="IP">客户端联接IP</param> ''' <param name="Port">客户端联接端口号</param> ''' <remarks></remarks> Private Sub GetClientClose(ByVal IP As String,ByVal Port As String) Try If _Clients.ContainsKey(IP & "\&" & Port) Then SyncLock _Clients.SyncRoot '_Clients.Item(IP & "\&" & Port) _Clients.Remove(IP & "\&" & Port) End SyncLock End If RaiseEvent ClientClose(IP,Port) Catch ex As Exception RaiseEvent Exception(ex) End Try End Sub #End Region #Region "向客户端发送数据" ''' <summary> ''' 向客户端发送信息 ''' </summary> ''' <param name="value">发送的内容</param> ''' <param name="IPAddress">IP地址</param> ''' <param name="Port">端口号</param> ''' <returns> Boolean</returns> ''' <remarks></remarks> Public Function SendData(ByVal value As Byte(),ByVal Port As String) As Boolean Try Dim clientSocket As System.Net.Sockets.Socket clientSocket = _Clients.Item(IPAddress & "\&" & Port) clientSocket.Send(value,SocketFlags.None) Return True Catch ex As Exception RaiseEvent Exception(ex) Return False End Try End Function Public Function SendFile(ByVal value As String,ByVal Port As String) As Boolean Try Dim clientSocket As System.Net.Sockets.Socket clientSocket = _Clients.Item(IPAddress & "\&" & Port) clientSocket.SendFile(value) Return True Catch ex As Exception RaiseEvent Exception(ex) Return False End Try End Function Public Function SendDataToAllClient(ByVal value As Byte()) As Boolean Try For Each clientSocket As System.Net.Sockets.Socket In _Clients.Values clientSocket.Send(value,SocketFlags.None) Next Return True Catch ex As Exception RaiseEvent Exception(ex) Return False End Try End Function #End Region ''' <summary> ''' 得到客户端的Socket联接 ''' </summary> ''' <param name="IPAddress">客户端的IP</param> ''' <param name="Port">客户端的端口号</param> ''' <returns>Socket联接</returns> ''' <remarks></remarks> Private Function GetClientSocket(ByVal IPAddress As String,ByVal Port As String) As Socket Try Dim ClientSocket As Socket ClientSocket = _Clients.Item(IPAddress & "\&" & Port) Return ClientSocket Catch ex As Exception RaiseEvent Exception(ex) Return Nothing End Try End Function #End Region Private Class ClientCommunication Public Event Exception(ByVal ex As Exception) Private ServerSocket As New System.Net.Sockets.Socket(AddressFamily.InterNetwork,ProtocolType.Tcp) Private myClientSocket As New System.Net.Sockets.Socket(AddressFamily.InterNetwork,ProtocolType.Tcp) Private myParentObject As TCPServer Private oldbytes() As Byte Private _IPAddress,_Port As String Private NclientInfoT As IPEndPoint = Nothing Private iLen As Integer Private allDone As New ManualResetEvent(False) ''' <summary> ''' 实例ClientCommunication类 ''' </summary> ''' <param name="ServerSocket"></param> ''' <param name="ClientSocket"></param> ''' <param name="ParentObject"></param> ''' <remarks></remarks> Public Sub New(ByVal ServerSocket As Socket,ByVal ClientSocket As Socket,ByVal ParentObject As TCPServer) Me.ServerSocket = ServerSocket myClientSocket = ClientSocket myParentObject = ParentObject NclientInfoT = CType(myClientSocket.RemoteEndPoint,IPEndPoint) _IPAddress = NclientInfoT.Address.ToString _Port = NclientInfoT.Port.ToString End Sub ''' <summary> ''' 客户端通讯主线程 ''' </summary> ''' <remarks></remarks> Public Sub serverThreadProc() Try Dim sb As New SocketAndBuffer sb.Socket = myClientSocket sb.Socket.BeginReceive(sb.Buffer,AddressOf ReceiveCallBack,sb) 'allDone.WaitOne() Catch ex As Exception RaiseEvent Exception(ex) End Try End Sub ''' <summary> ''' socket异步接收回调函数 ''' </summary> ''' <param name="ar"></param> ''' <remarks></remarks> Private Sub ReceiveCallBack(ByVal ar As IAsyncResult) Dim sb As SocketAndBuffer allDone.Set() sb = CType(ar.AsyncState,SocketAndBuffer) Try If sb.Socket.Connected Then iLen = sb.Socket.EndReceive(ar) If iLen > 0 Then ReDim oldbytes(iLen - 1) Array.Copy(sb.Buffer,iLen) myParentObject.GetData_Byte(oldbytes,_Port) sb.Socket.BeginReceive(sb.Buffer,sb) Else If (Not myClientSocket Is Nothing) Then If myClientSocket.Connected Then myClientSocket.Close() Else myClientSocket.Close() End If myClientSocket = Nothing If Not NclientInfoT Is Nothing Then myParentObject._Clients.Remove(_IPAddress & "\&" & _Port) myParentObject.GetClientClose(_IPAddress,_Port) End If End If End If End If Catch ex As Exception If (Not myClientSocket Is Nothing) Then If myClientSocket.Connected Then myClientSocket.Close() Else myClientSocket.Close() End If myClientSocket = Nothing If Not NclientInfoT Is Nothing Then myParentObject._Clients.Remove(_IPAddress & "\&" & _Port) myParentObject.GetClientClose(_IPAddress,_Port) End If End If RaiseEvent Exception(ex) End Try End Sub ''' <summary> ''' 异步操作socket缓冲类 ''' </summary> ''' <remarks></remarks> Private Class SocketAndBuffer Public Socket As System.Net.Sockets.Socket Public Buffer(8192) As Byte End Class End Class End Class
2)TCP 客户端连接通信类
- ImportsSystem.Net
- ImportsSystem.Net.Sockets
- ImportsSystem.Threading
- PublicClassTCPClient
- #Region"私有成员"
- Private_LocationClientSocketAsSocket'本地侦听服务
- Private_LocalPortAsString'本地端口
- Private_LocalHostNameAsString
- Private_LocalIPAsString
- PrivateautoEventAsAutoResetEvent
- Private_RemoteHostNameAsString'遠程端計算機名
- Private_RemoteIPAsString'遠程端計算機IP
- Private_RemotePortAsString'遠程端計算機Port
- Private_RemoteIPOrHostNameAsString
- 'Private_MaxClientAsInteger'最大客户端连接数
- 'Private_ClientsAsNewSortedList'客户端队列
- 'Private_ListenThreadAsThread=Nothing'侦听线程
- 'Private_ServerStartAsBoolean=False'服务器是否已经启动
- Private_RecvMaxAsInteger'接收缓冲区大小
- PrivateClientThreadAsThread
- 'PrivateClitenStreamAsNetworkStream
- PrivateIsStopAsBoolean=False
- #EndRegion
- #Region"事件"
- '''<summary>
- '''客户端联接事件
- '''</summary>
- '''<remarks></remarks>
- PublicEventClientConnected()
- '''<summary>
- '''客户端断开事件
- '''</summary>
- '''<remarks></remarks>
- PublicEventClientClosed()
- '''<summary>
- '''接收到客户端的数据
- '''</summary>
- '''<paramname="value">数据</param>
- '''<remarks></remarks>
- PublicEventDataArrived(ByValvalueAsByte(),ByValLenAsInteger)
- '''<summary>
- '''异常数据
- '''</summary>
- '''<paramname="ex"></param>
- '''<remarks></remarks>
- PublicEventException(ByValexAsException)
- #EndRegion
- #Region"属性"
- '''<summary>
- '''是否已經連接
- '''</summary>
- '''<value></value>
- '''<returns></returns>
- '''<remarks></remarks>
- PublicReadOnlyPropertyConnected()AsBoolean
- Get
- Return_LocationClientSocket.Connected
- EndGet
- EndProperty
- '''<summary>
- '''本地計算機名稱
- '''</summary>
- '''<value></value>
- '''<returns></returns>
- '''<remarks></remarks>
- PublicReadOnlyPropertyLocalHostName()AsString
- Get
- Return_LocalHostName
- EndGet
- EndProperty
- '''<summary>
- '''本地計算IP
- '''</summary>
- '''<value></value>
- '''<returns></returns>
- '''<remarks></remarks>
- PublicReadOnlyPropertyLocalIP()AsString
- Get
- Return_LocalIP
- EndGet
- EndProperty
- '''<summary>
- '''本地計算機端口
- '''</summary>
- '''<value></value>
- '''<returns></returns>
- '''<remarks></remarks>
- PublicReadOnlyPropertyLocalPort()AsString
- Get
- Return_LocalPort
- EndGet
- EndProperty
- '''<summary>
- '''遠程計算機IP
- '''</summary>
- '''<value></value>
- '''<returns></returns>
- '''<remarks></remarks>
- PublicReadOnlyPropertyRemoteIP()AsString
- Get
- Return_RemoteIP
- EndGet
- EndProperty
- '''<summary>
- '''遠程計算機端口
- '''</summary>
- '''<value></value>
- '''<returns></returns>
- '''<remarks></remarks>
- PublicReadOnlyPropertyRemotePort()AsString
- Get
- Return_RemotePort
- EndGet
- EndProperty
- '''<summary>
- '''遠程計算機名稱
- '''</summary>
- '''<value></value>
- '''<returns></returns>
- '''<remarks></remarks>
- PublicReadOnlyPropertyRemoteHostName()AsString
- Get
- Return_RemoteHostName
- EndGet
- EndProperty
- #EndRegion
- #Region"方法"
- '''<summary>
- '''实例 TCPServer
- '''</summary>
- '''<paramname="RemoteIPOrHostName">需要連接服務的IP地址或計算機名稱</param>
- '''<paramname="Port">侦听客户端联接的端口号</param>
- '''<paramname="RecvMax">接收缓冲区大小</param>
- '''<paramname="RecvSleep">接收线程睡眠时间</param>
- '''<remarks></remarks>
- SubNew(ByValRemoteIPOrHostNameAsString,ByValPortAsString,ByValRecvSleepAsInteger)
- Try
- _LocalHostName=Dns.GetHostName()
- '_RemoteIP=Dns.GetHostAddresses(RemoteIPOrHostName)(0).ToString
- _RemotePort=Port
- _RecvMax=RecvMax
- _RemoteIPOrHostName=RemoteIPOrHostName
- _RemotePort=Port
- 'DimstrServerHostAsNewIPEndPoint(IPAddress.Any,Int32.Parse(_ListenPort))
- '建立TCP侦听
- _LocationClientSocket=NewSocket(AddressFamily.InterNetwork,ProtocolType.Tcp)
- autoEvent=NewAutoResetEvent(False)
- DimcThreadAsNewThread(NewThreadStart(AddressOfConnectHost))
- cThread.Start()
- autoEvent.WaitOne(1000,False)
- cThread.Abort()
- CatchexAsException
- RaiseEventException(ex)
- EndTry
- EndSub
- PublicSubConnectHost()
- Try
- DimremoteIPAsNet.IPAddress=Nothing
- IfIPAddress.TryParse(_RemoteIPOrHostName,remoteIP)Then
- '_LocationClientSocket.BeginConnect()
- _LocationClientSocket.Connect(remoteIP,_RemotePort)
- '_RemoteIP=RemoteHostName
- Else
- _LocationClientSocket.Connect(_RemoteIPOrHostName,_RemotePort)
- _RemoteHostName=RemoteHostName
- EndIf
- If_LocationClientSocket.ConnectedThen
- _LocationClientSocket.SendBufferSize=_RecvMax
- _LocationClientSocket.ReceiveBufferSize=_RecvMax
- DimclientInfoTAsIPEndPoint
- clientInfoT=CType(_LocationClientSocket.RemoteEndPoint,IPEndPoint)
- _RemoteIP=clientInfoT.Address.ToString
- 'DimremoteHostAsNet.IPHostEntry
- _RemoteHostName=Dns.GetHostEntry(_RemoteIP).HostName
- clientInfoT=CType(_LocationClientSocket.LocalEndPoint,IPEndPoint)
- _LocalIP=clientInfoT.Address.ToString
- _LocalPort=clientInfoT.Port.ToString
- IsStop=False
- RaiseEventClientConnected()
- ClientThread=NewThread(NewThreadStart(AddressOfClientListen))
- ClientThread.Start()
- autoEvent.Set()
- EndIf
- CatchexAsException
- EndTry
- EndSub
- '''<summary>
- '''關閉客戶端連接
- '''</summary>
- '''<remarks></remarks>
- PublicSubClose()
- Try
- If_LocationClientSocketIsNothingThenExitSub
- IsStop=True
- IfNotClientThreadIsNothingThen
- Thread.Sleep(5)
- ClientThread.Abort()
- EndIf
- _LocationClientSocket.Close()
- _LocationClientSocket=Nothing
- ClientThread=Nothing
- RaiseEventClientClosed()
- CatchexAsException
- RaiseEventException(ex)
- EndTry
- EndSub
- '''<summary>
- '''实例 TCPServer
- '''</summary>
- '''<paramname="value">發送的資料,二進制數組</param>
- '''<remarks></remarks>
- PublicFunctionSendData(ByValvalueAsByte())AsBoolean
- Try
- _LocationClientSocket.Send(value)
- CatchexAsException
- RaiseEventException(ex)
- EndTry
- EndFunction
- PrivateSubClientListen()
- DimtmpByt(8192)AsByte
- DimrecData()AsByte
- DimRAsInteger
- WhileNotIsStop
- Try
- If_LocationClientSocket.Poll(50,SelectMode.SelectWrite)Then
- R=_LocationClientSocket.Receive(tmpByt)
- IfR>0Then
- ReDimrecData(R-1)
- Array.Copy(tmpByt,recData,R)
- RaiseEventDataArrived(recData,recData.Length)
- Else
- If(Not_LocationClientSocketIsNothing)Then
- _LocationClientSocket.Close()
- _LocationClientSocket=Nothing
- IsStop=True
- RaiseEventClientClosed()
- EndIf
- EndIf
- EndIf
- CatchsexAsSocketException
- Ifsex.ErrorCode=10054Then
- If(Not_LocationClientSocketIsNothing)Then
- _LocationClientSocket.Close()
- _LocationClientSocket=Nothing
- IsStop=True
- RaiseEventClientClosed()
- EndIf
- Else
- RaiseEventException(sex)
- EndIf
- CatchexAsException
- RaiseEventException(ex)
- EndTry
- EndWhile
- EndSub
- #EndRegion
- EndClass
Imports System.Net Imports System.Net.Sockets Imports System.Threading Public Class TCPClient #Region "私有成员" Private _LocationClientSocket As Socket '本地侦听服务 Private _LocalPort As String '本地端口 Private _LocalHostName As String Private _LocalIP As String Private autoEvent As AutoResetEvent Private _RemoteHostName As String '遠程端計算機名 Private _RemoteIP As String '遠程端計算機IP Private _RemotePort As String '遠程端計算機Port Private _RemoteIPOrHostName As String 'Private _MaxClient As Integer '最大客户端连接数 'Private _Clients As New SortedList '客户端队列 'Private _ListenThread As Thread = Nothing '侦听线程 'Private _ServerStart As Boolean = False '服务器是否已经启动 Private _RecvMax As Integer '接收缓冲区大小 Private ClientThread As Thread 'Private ClitenStream As NetworkStream Private IsStop As Boolean = False #End Region #Region "事件" ''' <summary> ''' 客户端联接事件 ''' </summary> ''' <remarks></remarks> Public Event ClientConnected() ''' <summary> ''' 客户端断开事件 ''' </summary> ''' <remarks></remarks> Public Event ClientClosed() ''' <summary> ''' 接收到客户端的数据 ''' </summary> ''' <param name="value">数据</param> ''' <remarks></remarks> Public Event DataArrived(ByVal value As Byte(),ByVal Len As Integer) ''' <summary> ''' 异常数据 ''' </summary> ''' <param name="ex"></param> ''' <remarks></remarks> Public Event Exception(ByVal ex As Exception) #End Region #Region "属性" ''' <summary> ''' 是否已經連接 ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property Connected() As Boolean Get Return _LocationClientSocket.Connected End Get End Property ''' <summary> ''' 本地計算機名稱 ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property LocalHostName() As String Get Return _LocalHostName End Get End Property ''' <summary> ''' 本地計算IP ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property LocalIP() As String Get Return _LocalIP End Get End Property ''' <summary> ''' 本地計算機端口 ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property LocalPort() As String Get Return _LocalPort End Get End Property ''' <summary> ''' 遠程計算機IP ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property RemoteIP() As String Get Return _RemoteIP End Get End Property ''' <summary> ''' 遠程計算機端口 ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property RemotePort() As String Get Return _RemotePort End Get End Property ''' <summary> ''' 遠程計算機名稱 ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public ReadOnly Property RemoteHostName() As String Get Return _RemoteHostName End Get End Property #End Region #Region "方法" ''' <summary> ''' 实例 TCPServer ''' </summary> ''' <param name="RemoteIPOrHostName">需要連接服務的IP地址或計算機名稱</param> ''' <param name="Port">侦听客户端联接的端口号</param> ''' <param name="RecvMax">接收缓冲区大小</param> ''' <param name="RecvSleep">接收线程睡眠时间</param> ''' <remarks></remarks> Sub New(ByVal RemoteIPOrHostName As String,ByVal Port As String,ByVal RecvSleep As Integer) Try _LocalHostName = Dns.GetHostName() '_RemoteIP = Dns.GetHostAddresses(RemoteIPOrHostName)(0).ToString _RemotePort = Port _RecvMax = RecvMax _RemoteIPOrHostName = RemoteIPOrHostName _RemotePort = Port 'Dim strServerHost As New IPEndPoint(IPAddress.Any,Int32.Parse(_ListenPort)) '建立TCP侦听 _LocationClientSocket = New Socket(AddressFamily.InterNetwork,ProtocolType.Tcp) autoEvent = New AutoResetEvent(False) Dim cThread As New Thread(New ThreadStart(AddressOf ConnectHost)) cThread.Start() autoEvent.WaitOne(1000,False) cThread.Abort() Catch ex As Exception RaiseEvent Exception(ex) End Try End Sub Public Sub ConnectHost() Try Dim remoteIP As Net.IPAddress = Nothing If IPAddress.TryParse(_RemoteIPOrHostName,remoteIP) Then '_LocationClientSocket.BeginConnect() _LocationClientSocket.Connect(remoteIP,_RemotePort) '_RemoteIP = RemoteHostName Else _LocationClientSocket.Connect(_RemoteIPOrHostName,_RemotePort) _RemoteHostName = RemoteHostName End If If _LocationClientSocket.Connected Then _LocationClientSocket.SendBufferSize = _RecvMax _LocationClientSocket.ReceiveBufferSize = _RecvMax Dim clientInfoT As IPEndPoint clientInfoT = CType(_LocationClientSocket.RemoteEndPoint,IPEndPoint) _RemoteIP = clientInfoT.Address.ToString 'Dim remoteHost As Net.IPHostEntry _RemoteHostName = Dns.GetHostEntry(_RemoteIP).HostName clientInfoT = CType(_LocationClientSocket.LocalEndPoint,IPEndPoint) _LocalIP = clientInfoT.Address.ToString _LocalPort = clientInfoT.Port.ToString IsStop = False RaiseEvent ClientConnected() ClientThread = New Thread(New ThreadStart(AddressOf ClientListen)) ClientThread.Start() autoEvent.Set() End If Catch ex As Exception End Try End Sub ''' <summary> ''' 關閉客戶端連接 ''' </summary> ''' <remarks></remarks> Public Sub Close() Try If _LocationClientSocket Is Nothing Then Exit Sub IsStop = True If Not ClientThread Is Nothing Then Thread.Sleep(5) ClientThread.Abort() End If _LocationClientSocket.Close() _LocationClientSocket = Nothing ClientThread = Nothing RaiseEvent ClientClosed() Catch ex As Exception RaiseEvent Exception(ex) End Try End Sub ''' <summary> ''' 实例 TCPServer ''' </summary> ''' <param name="value">發送的資料,二進制數組</param> ''' <remarks></remarks> Public Function SendData(ByVal value As Byte()) As Boolean Try _LocationClientSocket.Send(value) Catch ex As Exception RaiseEvent Exception(ex) End Try End Function Private Sub ClientListen() Dim tmpByt(8192) As Byte Dim recData() As Byte Dim R As Integer While Not IsStop Try If _LocationClientSocket.Poll(50,SelectMode.SelectWrite) Then R = _LocationClientSocket.Receive(tmpByt) If R > 0 Then ReDim recData(R - 1) Array.Copy(tmpByt,R) RaiseEvent DataArrived(recData,recData.Length) Else If (Not _LocationClientSocket Is Nothing) Then _LocationClientSocket.Close() _LocationClientSocket = Nothing IsStop = True RaiseEvent ClientClosed() End If End If End If Catch sex As SocketException If sex.ErrorCode = 10054 Then If (Not _LocationClientSocket Is Nothing) Then _LocationClientSocket.Close() _LocationClientSocket = Nothing IsStop = True RaiseEvent ClientClosed() End If Else RaiseEvent Exception(sex) End If Catch ex As Exception RaiseEvent Exception(ex) End Try End While End Sub #End Region End Class
窗体调用TCP 类如下
服务器端:
- PublicWithEventsMyClientAsTCPServer
Public WithEvents MyClient As TCPServer
客户机端:
- PublicWithEventsMyClientAsTCPClient
Public WithEvents MyClient As TCPClient