通过事件读取tcp

时间:2014-09-29 08:50:14

标签: c# events tcp modbus

我是C#的新手,我试图创建一个Modbus-TCP从站。

我想做的就是在从TCP Master接收数据时调用事件处理程序。

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;博士:当我的客户从主人那里收到数据时,我正在寻找引发事件的方法。

1 个答案:

答案 0 :(得分:0)

通常,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();
 }