我对网络编程不熟悉,正在尝试在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
最佳答案
@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。
它能给你任何线索吗?