通过事件读取tcp
本文关键字:tcp 读取 事件 | 更新日期: 2023-09-27 18:24:52
我对C#有点陌生,我正在尝试创建一个Modbus TCP从站。
当我从TCP主机接收数据时,我只想调用一个事件处理程序。
namespace Mark_II.Device
{
class Slave_TCP : mSlave
{
short trans_ID;
byte[] Respond;
byte[] MasterMessage;
TcpClient Client;
NetworkStream stream;
public Slave_TCP(String IP, int Port)
{
Client = new TcpClient(IP, Port);
stream = Client.GetStream();
// insert "call event handler" here<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
private void client_OnReceiveData(object sender, SerialDataReceivedEventArgs e)
{
byte[] message = new byte[Client.ReceiveBufferSize];
stream.Read(message, 0, message.Length);
}
}
}
我一直在四处寻找,但什么也找不到。。。请帮帮我。
tl;dr:我正在寻找一种方法,当我的客户端接收到来自master的数据时,引发一个事件。
通常,C#中的事件是这样工作的:
public delegate void MessageHandler(string message);
public class Client
{
public event MessageHandler MessageArrived;
public void CheckForMessage() //logic to check if message is received
{
//other code to check for message
if(MessageArrived != null)
MessageArrived("message received");
}
}
public class DisplayMessage
{
public void DisplayMessage(string message)
{
Console.WriteLine("Message: {0}", message);
}
}
连接事件的代码:
public class ProcessMessage
{
Client client = new Client();
DisplayMessage msg = new DisplayMessage();
client.MessageArrived += new MessageHandler(msg.DisplayMessage);
client.CheckForMessage();
}