TCP读写问题.net

时间:2012-05-15 11:29:55

标签: .net tcpclient tcplistener

我使用以下代码从特定服务器发送消息

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    send("Hello there")
    TextBox1.Text = TextBox1.Text + "Send Successful"
End Sub

Public Sub send(ByVal data As String)
    Dim tcpClient As New TcpClient()
    Try
        tcpClient.Connect("10.xxx.xx.xx", 7000)
        TextBox1.text = TextBox1.Text + "Conneecte"
    Catch e As Exception
        Console.WriteLine(e)
    End Try
    If tcpClient.Connected Then
        Dim networkStream As NetworkStream = tcpClient.GetStream()
        Dim streamWriter As New StreamWriter(networkStream)
        Console.WriteLine("Messege {0} to {1}", data, tcpClient.Client.RemoteEndPoint)
        streamWriter.WriteLine(data)
        streamWriter.Flush()
        tcpClient.Close()
    End If
End Sub

发送成功。

以下代码正在从另一个系统读取。并且代码在do while循环中挂起

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Dim tcpClient As New System.Net.Sockets.TcpClient()
    Try
        tcpClient.Connect("10.xxx.xx.xx", 7000)
        Dim networkStream As NetworkStream = tcpClient.GetStream()
        If networkStream.CanWrite And networkStream.CanRead Then
            'Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("$gimme")
            'networkStream.Write(sendBytes, 0, sendBytes.Length)
            ' 'Read the NetworkStream into a byte buffer.
            Do
            Loop Until networkStream.DataAvailable
            Dim bytes(tcpClient.ReceiveBufferSize) As Byte
            networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
            Dim returndata As String = Encoding.ASCII.GetString(bytes)
            ''Label1.Text = returndata
            tcpClient.Close()
        Else
            If Not networkStream.CanRead Then
                tcpClient.Close()
            Else
                If Not networkStream.CanWrite Then
                    tcpClient.Close()
                End If
            End If
        End If
    Catch ex As Exception
        'sLabel1.Text = "Exception Caught"
    End Try
End Sub

代码在读取部分中挂起

待办事项                 循环直到networkStream.DataAvailable

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

基于以下代码,您的代码逻辑似乎存在缺陷。

' Examples for CanRead, Read, and DataAvailable.
' Check to see if this NetworkStream is readable.
If myNetworkStream.CanRead Then
   Dim myReadBuffer(1024) As Byte
       Dim myCompleteMessage As StringBuilder = New StringBuilder()
   Dim numberOfBytesRead As Integer = 0

   ' Incoming message may be larger than the buffer size.
   Do
      numberOfBytesRead = myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length)
           myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead))
   Loop While myNetworkStream.DataAvailable

   ' Print out the received message to the console.
       Console.WriteLine(("You received the following message : " + myCompleteMessage.ToString()))
Else
   Console.WriteLine("Sorry.  You cannot read from this NetworkStream.")
End If

我建议你再考虑一下NetworkStream.DataAvailable Property

答案 1 :(得分:0)

问题是没有已知的方法可以立即读取所有字节,而不会阻塞read()。 要以 inputstream.ReadLine()的方式读取一行,最好逐个字符地读取,直到读取行尾字符为止:

Function readln(ByRef inputstream as Stream) as String
 Dim r as String = ""
 do
  Dim c as Char = Chr(inputstream.Read())
  If c = vbCr Then Exit loop    'vbCr or vbLf depending on application'
  r += c
 loop
 Return r
End Function

不好但功能齐全。当数据缓慢或迟到时,不会消耗CPU性能。 inputstream.Read()为您阻止,直到某个角色可用为止。