2017-02-01 3 views
1

ユニティプロジェクト内で、このC#TCPサーバーの例を使用して理解代表団&コールバック

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

は、ノートは3つのコールバックイベントのOnConnect、OnDataAvailableとONERRORがありに言及します。 次のシグネチャ

private void tcpServer1_OnDataAvailable(tcpServer.TcpServerConnection connection) 

と2つのコールバックの例がありますが、私はこれらのコールバックを有効にするために、特別な、またはそれに加えて、何もする必要はありますかtcpServer1_OnDataAvailableが自動的に呼び出され、予約ハンドラ名をconsdieredされますか?

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

コールバックを 'TCPServer'タイプのイベントで登録する必要があります。 –

+0

msdnを見てください。コード内のソケットクラスを、TcpClientやTcpListenerなどのソケットクラスを継承する任意のクラスに置き換えることができます。https://msdn.microsoft.com/en-us/library/w89fhyex(v=vs.110).aspx – jdweng

答えて

0

イベントハンドラデリゲートを特定のイベントに登録する必要があります。

TcpServer tcpServer1 = new TcpServer(); 

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


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

コールバックは、関心のあるイベントが発生したときに呼び出されるメソッドです。あなたは、実際にこのように、それらを設定する必要があります:

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でインスタンス化された時点の後に、コンストラクタでこのコードを配置する必要があります。

関連する問題