我创建了一个 TCP 服务器侦听器,用于侦听一些作为 TCP 客户端连接的 IOT 设备。
TCP 服务器侦听器会工作几个小时,有时会工作一整天,然后突然停止侦听。我只是用来关闭和打开 WPF 应用程序然后它开始工作相同的时间和场景继续相同。
请你看看我的代码
public partial class MainWindow : Window
{
private TcpListener _TcpListener;
private TcpClient _TcpClient;
private bool _IsRun = false;
private int countRows = 0;
protected NetworkStream _NetStream;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(textPort.Text.Trim()))
{
int port = Convert.ToInt32(textPort.Text.Trim());
_TcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
_TcpListener.Start();
_IsRun = true;
this.btnListener.IsEnabled = false;
Print("Listener (" + port + ") was started");
new Task(() => {
while (_IsRun)
{
if (_TcpClient == null)
{
_TcpClient = _TcpListener.AcceptTcpClient();
Print("A new connected! remote:" + _TcpClient.Client.RemoteEndPoint.ToString());
_NetStream = _TcpClient.GetStream();
}
if (_TcpClient.Connected && _NetStream.DataAvailable)
{
byte[] buffer = null;
buffer = new byte[_TcpClient.Available];
_NetStream.Read(buffer, 0, buffer.Length);
string hexString = BitConverter.ToString(buffer, 0, buffer.Length).Replace("-", "");
string asciiString = Encoding.ASCII.GetString(buffer, 0, buffer.Length).Trim('\0');
Print("HEX:" + hexString + " ASCII:" + asciiString);
//this method will receive the Byte data
Analysis(buffer);
}
}
}).Start();
}
}
private void Print(string msg)
{
if (countRows > 10)
{
this.textLog.Dispatcher.Invoke(new Action(() =>
{
this.textLog.Document.Blocks.Clear();
}));
countRows = 0;
}
msg = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ": " + msg + "\r";
this.textLog.Dispatcher.Invoke(new Action(() =>
{
this.textLog.AppendText(msg);
this.textLog.ScrollToEnd();
countRows += 1;
}));
}
}