Welcome

首页 / 软件开发 / VB.NET / 游戏大厅从基础开始(3.5)——客户端与服务器的连接

游戏大厅从基础开始(3.5)——客户端与服务器的连接2010-01-04 cnblogs 韦恩卑鄙可能要犯大忌讳 本次只有代码 所以补充两句

正在实现策略模式的constructor 所以最 近没有时间整理注释

大家凑合看 随后补说明

Code

Namespace Communicate.TCP
Class TCPLinkListener
Inherits Global.WayneGameSolution.Communicate.LinkListener
Public Shared ReadOnly propertyKeys As String() = {"Port", "TimeoutSecond", "LinkProveString"}
Public TCPListener As System.Net.Sockets.TcpListener
Private ClientLinkProvePool As New LinkedList(Of IClientLink)
Sub New(ByVal Parms As XElement)
MyBase.new(Parms)
Dim p As Int32
"todo: 各种本地化资源
Dim NotAvailableProperties As IEnumerable(Of String) = From key As String In propertyKeys Select key Where Not _ParmsDic.ContainsKey(key)
If NotAvailableProperties.Count > 0 Then
Throw New CommunicateException(String.Format(My.Resources.Communicate_TCPLinkListener_Parms_Error_Message, String.Join(",", propertyKeys), propertyKeys.Length, String.Join(",", NotAvailableProperties.ToArray())))
End If
If Port = -1 Then
Throw New CommunicateException((My.Resources.Communicate_TCPLinkListener_Parms_Port_Error_Message))
End If
If Not Int32.TryParse(Port, p) Then
Throw New CommunicateException("no int port")
End If
TCPListener = New System.Net.Sockets.TcpListener(Net.IPAddress.Any, p)
TCPListener.Start()
TCPListener.BeginAcceptSocket(AddressOf TCPListener_AcceptSocket, TCPListener)
End Sub
Sub TCPListener_AcceptSocket(ByVal o As IAsyncResult)
CheckTimeoutedLinks()
Dim socket As System.Net.Sockets.Socket = TCPListener.EndAcceptSocket(o)
Dim clk As New TCPClientLink(socket, TimeoutSecond, LinkProveString)
ClientLinkProvePool.AddLast(clk)
TCPListener.BeginAcceptSocket(AddressOf TCPListener_AcceptSocket, TCPListener)
End Sub
Private Sub CheckTimeoutedLinks()
Dim lk As TCPClientLink
Do While ClientLinkProvePool.Count > 0
lk = ClientLinkProvePool.First().Value
If lk.LastDataTime.AddSeconds(TimeoutSecond) < Now Then
ClientLinkProvePool.RemoveFirst()
If Not lk.IsLinkProved Then
lk.Close()
End If
Else
Exit Do
End If
Loop
End Sub
ReadOnly Property Port() As Int32
Get
Dim p As Int32
If Int32.TryParse(ParmsDic("Port"), p) Then
Return p
Else
Return -1
End If
End Get
End Property
ReadOnly Property TimeoutSecond() As Int32
Get
Dim t As Int32
If Int32.TryParse(ParmsDic("TimeoutSecond"), t) Then
Return t
Else
Return -1
End If
End Get
End Property
ReadOnly Property LinkProveString() As String
Get
Return ParmsDic("LinkProveString")
End Get
End Property
End Class
End Namespace