1

关于这部分代码,我一直在努力。NullReferenceException 仅在运行时发生。

Public Sub SendData(ByVal b As String)
    Dim data(2048) As Byte
    data = System.Text.Encoding.ASCII.GetBytes(b)
    stream.Write(data, 0, data.Length)
End Sub

目的是获取一个字符串,并将字符串的字节流式传输到另一台计算机。代码的 stream.Write 部分是抛出 NullReferenceException 部分的原因。但是,我通过调试检查数据部分确实从代码的编码部分获取字节。所以我不确定它为什么会抛出 NullReferenceException。

4

2 回答 2

1

您需要声明一个 New NetworkStream。另外,像这样调暗你的字节数组:

 Dim myBuffer() As Byte = Encoding.ASCII.GetBytes(b)
 myNetworkStream.Write(myBuffer, 0, myBuffer.Length) 
于 2013-06-10T05:00:44.903 回答
0

我的猜测是you haven't initialized您的stream对象带有new关键字。看这里

还有几件事:

1) Do not initialize your byte array yourself. Let this task done by the `GetBytes` to return an initialized array and just store it in a variable.

2) Before writing to stream always check if you get something in your stream or not. 

类似的东西:(未经测试

Public Sub SendData(ByVal b As String)
    If (b IsNot Nothing AndAlso Not String.IsNullOrEmpty(b)) Then
       Dim data() As Byte = System.Text.Encoding.ASCII.GetBytes(b) ' or use List<Byte> instead.
       If( data IsNot Nothing AndAlso data.Length > 0) Then stream.Write(data, 0, data.Length)
    Else
       ' Incoming data is empty
    End If

    ' Don't forget to close stream
End Sub

希望能帮助到你!

于 2013-06-10T05:51:11.407 回答