gpt4 book ai didi

C# TCP client read occasionally receives no data - 'nothing'

转载 作者:可可西里 更新时间:2023-11-01 02:57:59 27 4
gpt4 key购买 nike

我编写了一个与服务器通信的 TCP 客户端。在专用的“监听”线程中,我有如下代码。它应该只在有数据时才读取数据。 (if (stream.DataAvailable))

奇怪的是,有时我的程序会崩溃,因为流绝对不会读取任何数据。它将返回一个空的 string。更奇怪的是,如果我尝试在 handleResponse(string s) 函数中“捕获”一个空字符串,它不会被捕获。

    public void listenForResponses()
{
Console.WriteLine ("Listening...");
while (isConnected == true)
{
Thread.Sleep (updateRate);
String responseData = String.Empty;

if (stream.DataAvailable) {
Int32 bytes = stream.Read (data, 0, data.Length);
Console.WriteLine (" >> Data size = "+data.Length);
responseData = System.Text.Encoding.ASCII.GetString (data, 0, bytes);
output = responseData+"";
handleResponse (output);
}
if (isConnected == false) {
closeConnection ();
}
}
}

public void handleResponse(string msg)
{
Console.WriteLine ("Received: "+msg);
iterateThroughEachCharInString (msg);
if ((msg != "")&&(msg != null)&&(msg != " ")) {
JSONDataObject desrlzdResp = JsonConvert.DeserializeObject<JSONDataObject>(msg);

if ((desrlzdResp.instruction != null)) {
if (desrlzdResp.instruction == "TestConn") {
handleTestConn (desrlzdResp);
} else if (desrlzdResp.instruction == "SceneOver") {
handleSceneFinished (desrlzdResp);
}
}
}
}

handleResponse 函数if ((desrlzdResp.instruction != null))System.NullReferenceException 抛出的异常

最佳答案

Network Streams 有一个习惯,即使在它们不活跃时也会公布可用的数据。此外,除非发送方事先通告,否则接收方无法知道传入流的长度。

        /// <summary>
/// Method designed to allow the sending of Byte[] data to the Peer
/// Because this is using NetworkStreams - the first 4 bytes sent is the data length
/// </summary>
/// <param name="TheMessage"></param>
public void SendBytesToPeer(byte[] TheMessage)
{

try
{
long len = TheMessage.Length;

byte[] Bytelen = BitConverter.GetBytes(len);

PeerStream.Write(Bytelen, 0, Bytelen.Length);
PeerStream.Flush();
PeerStream.Write(TheMessage, 0, TheMessage.Length);
PeerStream.Flush();
}
catch (Exception e)
{
//System.Windows.Forms.MessageBox.Show(e.ToString());
}
}

注意 - 发送端的刷新可能不需要,但我添加它是因为它没有害处 - Microsoft 说刷新对网络流没有任何作用。

因此此代码将确定您要发送的消息的大小,然后在“实际”消息之前将其发送给接收者。

        /// <summary>
/// Incoming bytes are retrieved in this method
/// </summary>
/// <param name="disconnected"></param>
/// <returns></returns>
private byte[] ReceivedBytes(ref bool disconnected)
{
try
{
//byte[] myReadBuffer = new byte[1024];
int receivedDataLength = 0;
byte[] data = { };
int len = 0;
int i = 0;
PeerStream.ReadTimeout = 15000;


if (PeerStream.CanRead)
{
//networkStream.Read(byteLen, 0, 8)
byte[] byteLen = new byte[8];
if (_client.Client.IsConnected() == false)
{
//Fire Disconnect event
if (OnDisconnect != null)
{
disconnected = true;
OnDisconnect(this);
return null;
}
}
while (len == 0)
{
PeerStream.Read(byteLen, 0, 8);

len = BitConverter.ToInt32(byteLen, 0);
}
data = new byte[len];

PeerStream.Read(data, receivedDataLength, len);

return data;
}



}
catch (Exception E)
{

//System.Windows.Forms.MessageBox.Show("Exception:" + E.ToString());
}
return null;
}

此代码将等到接收器检测到传入流的长度,然后它会尝试读取该确切长度。不要担心 OnDisconnect 位 - 这只是我从我正在做的项目中留下的一些代码。您可能需要考虑在 while(len == 0) 循环中添加一个 Thread.Sleep,以节省您的 CPU 周期。

关于C# TCP client read occasionally receives no data - 'nothing',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35012296/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com