Public Sub New(ByVal ip As String, ByVal port As Integer, ByVal frm As Object)
mainfrm = frm
Dim server As IPAddress = IPAddress.Parse(ip)
Dim tcp As New TcpClient()
Try
tcp.Connect(ip, port)
Catch generatedExceptionName As Exception
tcp = Nothing
End Try
If tcp Is Nothing Then
MsgBox("无法连接服务器,请重试")
Else
Dim netStream As NetworkStream = tcp.GetStream()
Dim loginInfo As String = System.Guid.NewGuid.ToString() & "|" & System.Net.Dns.GetHostName() '唯一标识 和 机器码
Dim stream() As Byte = Encoding.Unicode.GetBytes(loginInfo)
netStream.Write(stream, 0, stream.Length) '往服务器发送登录信息
Dim buffer As Byte() = New Byte(50) {}
netStream.Read(buffer, 0, buffer.Length) '得到回发的信息
Dim connResult As String = Encoding.Unicode.GetString(buffer).Substring(0, 2)
If connResult.Equals("OK") Then '登录成功
nStream = netStream
receiveThread = New Thread(New ParameterizedThreadStart(AddressOf ReceiveMsg))
receiveThread.Start(某端口号如24)
Else
MsgBox("登录失败……")
Return
End If
End If
End Sub
''' <summary>
''' 接受消息的线程执行体
''' </summary>
Private Sub ReceiveMsg(port As Integer)
msgbox(port)
While True
Dim packet As Byte() = New Byte(2) {}
nStream.Read(packet, 0, packet.Length)
Dim _cmd As String = String.Concat(packet(0), packet(1))
Select Case _cmd
'11状态,关闭客户端
Case "11"
mainfrm.Close()
If receiveThread IsNot Nothing Then
receiveThread.Abort()
End If
nStream.Close()
End Select
End While
End Sub