如何将以下代码行从VB.NET转换为C#。
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
我从developerfusion网站上获得了以下一行,但它在我的程序中给出了错误的结果。
byte[] bytes = new byte[tcpClient.ReceiveBufferSize + 1];
以下是我在Visual Basic中的整个代码示例。
Dim tcpClient As New System.Net.Sockets.TcpClient()
TcpClient.Connect(txtIP.Text, txtPort.Text)
Dim networkStream As NetworkStream = TcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(txtSend.Text.Trim())
networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.
TcpClient.ReceiveBufferSize = 52428800 '50 MB
'Do I need to clean the buffer?
'Get the string back (response)
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(TcpClient.ReceiveBufferSize))
' Output the data received from the host to the console.
Dim returndata As String = Encoding.ASCII.GetString(bytes)
答案 0 :(得分:1)
Visual Basic指定数组的最大边界而不是数组的长度(数组从索引0开始),因此您的转换添加了一个额外的字节。但是在你的代码中,正确的方法是:
byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
如果你得到错误的结果,请告诉我们到底出了什么问题。也许这是代码的另一部分。
修改:删除\ 0,如下所示:
byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
int bytesRead = networkStream.Read(bytes, 0, tcpClient.ReceiveBufferSize);
// Output the data received from the host to the console.
string returndata = Encoding.ASCII.GetString(bytes,0,bytesRead);
编辑:更好地读取数据包中的数据,因此您无需预先保留大缓冲区:
byte[] bytes = new byte[4096]; //buffer
int bytesRead = networkStream.Read(bytes, 0, bytes.Length);
while(bytesRead>0)
{
// Output the data received from the host to the console.
string returndata = Encoding.ASCII.GetString(bytes,0,bytesRead);
Console.Write(returndata);
bytesRead = networkStream.Read(bytes, 0, bytes.Length);
}