If recvStr = comStr Then Console.WriteLine("服务器超时.登陆失败!!") Return False End If
If Encoding.Unicode.GetString(data, 0, 4) = LOGINOK Then Console.WriteLine("登陆成功!!") Return True ElseIf Encoding.Unicode.GetString(data, 0, 4) = HVUSER Then Console.WriteLine("用户名重复.登陆失败!!") Return False Else Console.WriteLine("服务器未知错误,登陆失败!!") Return False End If
End Function
'登出函数 Private Sub exitApp()
Dim loginOutStr As String = LOGINOUT & username Dim sendBytes As [Byte]() = Encoding.Unicode.GetBytes(loginOutStr) ClientSocket.SendTo(sendBytes, ServerEP)
End Sub
'请求好友列表的函数 Private Function getU() As Boolean
getUDone = New ManualResetEvent(False) Dim getUbytes As Byte() = Encoding.Unicode.GetBytes(GETULIST) ClientSocket.SendTo(getUbytes, ServerEP)
Dim data As [Byte]() = New Byte(4056) {} Dim comStr As String = Encoding.Unicode.GetString(data, 0, 4)
Dim GUrecv As New myMethodDelegate(AddressOf recvGetU) GUrecv.BeginInvoke(data, Nothing, Nothing)
getUDone.WaitOne(30000, True)
Dim recvStr As String = Encoding.Unicode.GetString(data, 0, 4)
If recvStr = comStr Then Console.WriteLine("服务器超时.或取好友名单失败!!") Return False End If
If Encoding.Unicode.GetString(data, 0, 4) = GETUSER Then getUserList(data, getUrecCount) Console.WriteLine("获取在线名单成功!!") showUserList() Return True Else Console.WriteLine("服务器未知错误,获取在线名单失败!!") Return False End If
End Function
'登陆时用来异步的接收服务器发送的消息 Sub recvLogin(ByRef inData As Byte())
ClientSocket.Receive(inData) receiveDone.Set()
End Sub
'请求好友名单时用来异步接收服务器发送的消息 Sub recvGetU(ByRef inData As Byte())
getUrecCount = ClientSocket.Receive(inData) getUDone.Set()
End Sub
'处理收到的在线用户信息 Private Sub getUserList(ByVal userInfobytes() As Byte, ByVal reccount As Integer)
Dim ustr As String = Encoding.Unicode.GetString(userInfobytes, 4, reccount - 4)
Dim splitStr() As String = Nothing
splitStr = Ustr.Split("|")
Dim IPEPSplit() As String = Nothing
Dim i As Integer = 0
Dim k As Integer For k = 0 To splitStr.Length - 2 Step 2 ReDim Preserve OLUserName(i) ReDim Preserve OLUserEP(i)
OLUserName(i) = splitStr(k) IPEPSplit = splitStr(k + 1).Split(":") OLUserEP(i) = New IPEndPoint(IPAddress.Parse(IPEPSplit(0)), IPEPSplit(1))
IPEPSplit = Nothing i += 1 Next
End Sub
'显示在线用户 Private Sub showUserList() Dim i As Integer For i = 0 To OLUserName.Length - 1 If OLUserName(i) <> "" Then Console.WriteLine("用户名:" & OLUserName(i) & " 用户IP:" & OLUserEP(i).ToString) End If Next End Sub
'客户程序监听的函数 Sub listen()
While True
Try Dim recv As Integer = 0 '收到的字节数 Dim data As [Byte]() = New Byte(1024) {} '缓冲区大小 Dim sender As New IPEndPoint(IPAddress.Any, 0) |