项目中要使用tcp通讯,接收事件想通过委托实现,发现Action非常好用
下面是网络通讯部分代码
using BeetleX;
using BeetleX.Clients;
using InfusionBagSmartLabeler;
using InfusionBagSmartLabeler.utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace InfusionBagSmartLaber.Communication
{
public class TCPCamera
{
private TcpClient client;
private bool TaskIsRunning = true;
private Thread newThread = null;
static TCPCamera instance;
public Action<string> ReceiveTCP;
public static TCPCamera getInstance()
{
if (instance == null)
{
instance = new TCPCamera();
}
return instance;
}
public void Connect()
{
newThread = new Thread(connectNetwork);
newThread.IsBackground = true;
newThread.Start();
}
private void connectNetwork()
{
string strmsg1 = $"0 { util.GetNow()} connectCamera ";
Debug.WriteLine(strmsg1);
App.Log.Info(strmsg1);
string IP = Config.getInstance().getConfig("CameraIP");
int Port = Convert.ToInt32(Config.getInstance().getConfig("CameraPort"));
if (client == null)
{
client = SocketFactory.CreateClient<TcpClient>(IP, Port);
client.TimeOut = 300000;
}
while (TaskIsRunning)
{
try
{
var read = client.Receive();
var str = read.ReadToEnd();
ReceiveTCP(str);
}
catch (Exception e)
{
string msg = $"Camera ErrMSG new : { e.Message} HResult: {e.HResult}";
Debug.WriteLine(msg);
App.Log.Error(msg);
}
}
}
public void Send(string cmd)
{
// Debug.WriteLine(string.Format("0 {0} 发送命令给相机 SendCamera cmd = {1} ", util.GetNow(), cmd));
try
{
if (client.IsConnected)
{
client.Stream.ToPipeStream().Write(cmd);
client.Stream.Flush();
}
}
catch (Exception ex)
{
string msg = $"SendCamera ERROR {ex.Message}";
Debug.WriteLine(msg);
App.Log.Error(msg);
}
}
public void Dispose()
{
TaskIsRunning = false;
client.DisConnect();
client.Dispose();
client = null;
}
}
}
2.main窗体的代码
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//连接TCPCamera
TCPCamera.getInstance().Connect();
TCPCamera.getInstance().ReceiveTCP += ReceiveTCP;
}
public void ReceiveTCP(string cmd)
{
Debug.WriteLine($" Action ReceiveTCP {cmd}");
}