我是网络编程的新手,并且正在尝试在ICE API测试服务器和我的应用程序之间建立通信。当我尝试登录服务器时,下面的代码只能运行一次。换句话说,当我发送登录信息时,服务器会通过成功登录回复我。一旦我得到这个,我发送下一条消息到服务器,但作为回复我得到0,这意味着服务器已经断开连接。有人可以看看我的客户逻辑,并指出正确的方向,为什么上面的情况发生。请帮我解决这个问题,因为我已经过了几天没有结果。谢谢。
Public Function connect() As Boolean
bConnected = True
Dim port As Int32 = Convert.ToInt32("80")
Dim server As String = "63.247.113.201"
Try
objClient = New System.Net.Sockets.TcpClient(server, port)
objClient.NoDelay = False
objClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, 1)
objClient.GetStream.BeginRead(byReadBuffer, 0, BYTES_TO_READ, New AsyncCallback(AddressOf doRead), Nothing)
Catch ex As Exception
RaiseEvent exErr(ex.ToString)
bConnected = False
End Try
Return bConnected
End Function
Public Function DoTCPRequest(ByVal data As String, ByVal resetSession As Boolean) As String
Dim objSw As IO.StreamWriter
Try
objSw = New IO.StreamWriter(objClient.GetStream)
objSw.Write(data & vbCrLf)
objSw.Flush()
Console.WriteLine("Sent:" + data)
Catch ex As Exception
RaiseEvent exErr(ex.ToString)
End Try
objClient.GetStream.BeginRead(byReadBuffer, 0, BYTES_TO_READ, AddressOf Me.doRead, Nothing)
Return System.Text.Encoding.UTF8.GetString(byReadBuffer, 0, BYTES_TO_READ)
End Function
Private Sub doRead(ByVal ar As System.IAsyncResult)
Dim nTotalRead As Integer
Try
Try
nTotalRead = objClient.GetStream.EndRead(ar) Catch ex As Exception
RaiseEvent exErr(ex.ToString)
End Try
If nTotalRead > 0 Then
Dim szReceivedString As String = System.Text.Encoding.UTF8.GetString(byReadBuffer, 0, nTotalRead)
RaiseEvent dataReceived(szReceivedString)
Console.WriteLine("Recv1:" + szReceivedString)
End If
objClient.GetStream.BeginRead(byReadBuffer, 0, BYTES_TO_READ, New AsyncCallback(AddressOf doRead), Nothing)
Catch ex As Exception
RaiseEvent exErr(ex.ToString)
End Try
End Sub
答案 0 :(得分:0)
@lberezka,我在代码中看到一件奇怪的事情。是否要在DoRead()方法中查看以下代码行。
objClient.GetStream.BeginRead(byReadBuffer, 0, BYTES_TO_READ, New AsyncCallback(AddressOf doRead), Nothing) 'Begin the reading again.
理想情况下,在任何异步调用(Begin kind)中,回调句柄应该接收答案并尝试使用End方法结束调用。在您的情况下Stream.EndRead。
我在你的代码中看到的是你一遍又一遍地递归调用begin方法而且我没有在任何地方看到EndRead。
它能给你任何线索吗?