我有一个客户端应用程序(Windows窗体)同时发送/接收数据并将数据存储到队列中:一切正常,队列处理进展顺利。 断开远程主机(关闭连接按钮)并重新连接后:当发送方代码到达出列指令时出现错误“空队列”,我认为发送方类在重新启动连接后不具有与Receiver类相同的队列。 任何想法?
客户类:
public sealed partial class Client
{
private static Queue<byte[]> q = new Queue<byte[]>();
public void clear_q() { q.Clear(); }
public Client(string IPADRESStxt, string PORTNUMBERtxt)
{ _client = new TcpClient(IPADRESStxt, Int32.Parse(PORTNUMBERtxt)); }
public void SendData(byte[] data)
{ _sender.SendData(data); }
public event EventHandler<DataReceivedEventArgs> DataReceived;
public void Connect()
{
_stream = _client.GetStream();
_sender = new Sender(_stream);
_receiver = new Receiver(_stream);
_receiver.DataReceived += OnDataReceived;
}
public void Disconnect()
{ _stream.Close(); }
private void OnDataReceived(object sender, DataReceivedEventArgs e)
{
var handler = DataReceived;
if (handler != null) DataReceived(this, e); // re-raise event
}
private TcpClient _client;
private NetworkStream _stream;
private Receiver _receiver;
private Sender _sender;
private static ManualResetEvent ShutdownEvent = new ManualResetEvent(false);}
发件人类(数据已入队):
public sealed partial class Client
{
private sealed class Sender
{
internal void SendData(byte[] data)
{
_stream.Write(data, 0, data.Length);
}
internal Sender(NetworkStream stream)
{
_stream = stream;
_thread = new Thread(Run);
_thread.Start();
}
private void Run()
{
while (1 == 1)
{
lock (q)
{
if (q.Count > 0)
{
byte[] block1 = q.Dequeue(); //Error appears here
Sframe = new byte[] { 0x68, 0x04, 0x01, 0x00, 0x00, 0x00 };
SendData(Sframe);
// code
}
}
}
private NetworkStream _stream;
private Thread _thread;
}
}
}
接收者类(数据入队的地方):
public sealed partial class Client
{
private sealed class Receiver
{
internal event EventHandler<DataReceivedEventArgs> DataReceived;
internal Receiver(NetworkStream stream)
{
_stream = stream;
_thread = new Thread(Run);
_thread.Start();
}
private void Run()
{
try{
if (_stream.Read(m_Bytes, 0, m_Bytes.Length) > 0)
ReadFully(_stream);
else ShutdownEvent.Set();
}
finally
{
Thread.Sleep(1000);
_stream.Close();
}
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
byte[] newone = new byte[read];
ms.Write(buffer, 0, read);
Array.Copy(buffer, newone, read);
show_get_frame_one_by_one(newone);
}
return ms.ToArray();
}
}
public static void show_get_frame_one_by_one(byte[] buffer)
{
lock(q){ queing(buffer); update_queue_text(true); }
}
private NetworkStream _stream;
private Thread _thread;
}
}
Windows窗体:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
myform = this;
}
Client c1;
public void ConnectButton_Click(object sender, EventArgs e)
{
try
{
c1 = new Client(IPADRESStext.Text, PORTNUMBERtext.Text);
c1.Connect();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
private void CloseButton_Click(object sender, EventArgs e)
{
c1.Disconnect();
}
}