C# 了解代表,;回调

C# 了解代表,;回调,c#,callback,delegates,C#,Callback,Delegates,在Unity项目中使用此C#TCP服务器示例 注释中提到有3个回调事件OnConnect、OnDataAvailable和OnError。 有两个具有以下签名的回调示例 private void tcpServer1_OnDataAvailable(tcpServer.TcpServerConnection connection) 我是否需要执行任何特殊操作或除了启用这些回调之外的操作,或者tcpServer1\u OnDataAvailable是否使用自动调用的保留处理程序名称 TcpSe

在Unity项目中使用此C#TCP服务器示例

注释中提到有3个回调事件OnConnect、OnDataAvailable和OnError。 有两个具有以下签名的回调示例

private void tcpServer1_OnDataAvailable(tcpServer.TcpServerConnection connection)
我是否需要执行任何特殊操作或除了启用这些回调之外的操作,或者tcpServer1\u OnDataAvailable是否使用自动调用的保留处理程序名称

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

您需要注册特定事件的事件处理程序委托

TcpServer tcpServer1 = new TcpServer(); 

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


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

您需要注册特定事件的事件处理程序委托

TcpServer tcpServer1 = new TcpServer(); 

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


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

回调是在您感兴趣的事件发生时调用的方法。实际上,您确实需要设置它们,如下所示:

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
}

您应该在tcpServer1的变量用运算符new实例化的时间点之后,将此代码放入构造函数中。

回调是在您感兴趣的事件发生时调用的方法。实际上,您确实需要设置它们,如下所示:

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
}

在使用运算符new实例化tcpServer1的变量的时间点之后,您应该将此代码放入构造函数中。

您需要使用
TCPServer
typeLook at msdn中提供的事件注册回调。您可以将代码中的套接字类替换为继承套接字类的任何类,如TcpClient和TcpListener:您需要使用
TCPServer
typeLook at msdn中提供的事件注册回调。您可以将代码中的套接字类替换为继承套接字类的任何类,如TcpClient和TcpListener: