简体   繁体   中英

Understanding Delegates & Callbacks

Using this C# TCP Server example within a Unity project

https://www.codeproject.com/articles/488668/csharp-tcp-server

The notes mention There are 3 callback events OnConnect, OnDataAvailable and OnError. There are 2 callback examples with the following signatures

private void tcpServer1_OnDataAvailable(tcpServer.TcpServerConnection connection)

Do I need to do anything special or in addition to enable these callbacks or is tcpServer1_OnDataAvailable consdiered a reserved handler name that is automatically called?

TcpServer tcpServer1 = new TcpServer(); //in constructor (auto added if added as a component)

private void openTcpPort(int port)
{ 
    tcpServer1.Port = port;
    tcpServer1.Open();
}

private void closeTcpPort()
{
    tcpServer1.Close();
}  

You'll need to register the event handlers delegates to the specific events.

TcpServer tcpServer1 = new TcpServer(); 

// register event handler
tcpServer1.OnDataAvailable += tcpServer1_OnDataAvailable;


private void tcpServer1_OnDataAvailable(tcpServer.TcpServerConnection connection)
{
  // do work
}

Callbacks are methods that are called when an event you are interested in occurs. You do in fact need to set them up, like this:

tcpServer1.OnConnect += serverConnection => 
{
   //code to do stuff when a connection happens goes here
}

tcpServer1.OnDataAvailable += serverConnection =>
{
  //code to do stuff when data is available here
}

tcpServer1.OnError += serverConnection => 
{
   //code to do stuff when an error happens here
}

You should put this code in the constructor, after the point in time when tcpServer1's variable is instantiated with operator new.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM