4D 20 R8では、TCPConnectionクラスを導入し、リモートサーバーへのTCP接続を開始できるようになりました。4D v20 R9では、TCPListenerクラスが導入され、4Dで直接TCP接続を処理し、TCPサーバを構築することができるようになりました。
この2つのクラス-TCPConnectionとTCPListener-があれば、クライアント側とサーバ側の両方で、TCP通信を完全にコントロールすることができます。
この2つのクラスの使い方を説明します。
この記事に入る前に、TCPConnectionクラスに関する以前のブログ記事をチェックし、私たちが構築している基礎を理解することを強くお勧めします。
TCPListenerクラスとTCPConnectionクラスの相互作用
接続クラスの定義
前の例で使用したConnectionToTheServerクラスをモデルにして、ServerSideConnectionという新しいクラスを作成します。実装する主なコールバックの内訳は以下のとおりです:
Class constructor()
//Callback called when the connection is successfully established
Function onConnection($connection : 4D.TCPConnection; $event : 4D.TCPEvent)
ALERT("Connection established")
//Callback called when the connection is properly closed
Function onShutdown($connection : 4D.TCPConnection; $event : 4D.TCPEvent)
ALERT("Connection closed")
//Callback called when receiving data. The simple servers always send a sentence to show to the user
Function onData($connection : 4D.TCPConnection; $event : 4D.TCPEvent)
ALERT(BLOB to text($event.data; UTF8 text without length))
//Callback called when the connection is closed unexpectedly
Function onError($connection : 4D.TCPConnection; $event : 4D.TCPEvent)
ALERT("Connection error")
このクラスは、主要なTCPイベントに反応する単純なシェルです。
リスナー・クラスの設定
では、特定のポートで待ち受け、着信接続を受け付けるServerListenerクラスを作成しましょう:
property listener:4D.TCPListener
shared singleton Class constructor()
//Start listening to the port given as parameter
shared Function startListening($port:integer)
This.listener:=4D.TCPListener.new($port, This)
//Stop listening
shared Function stopListening()
This.listener.terminate()
//Callback called on a new incoming connection
Function onConnection($listener : 4D.TCPListener; $event : 4D.TCPEvent)->$result
ALERT("Listener: onConnection")
if ($event.IP = "a good IP address")
$result:=cs.ServerSideConnection.new()
else
$result := null
end if
//Callback called when an error prevents listening on the port (in general due to conflict with another application)
Function onError($listener : 4D.TCPListener; $event : 4D.TCPEvent)
ALERT("Listener: onError")
リスナーを開始するには
cs.ServerListener.me.startListening($port)
クライアントが接続を試みるたびに、onConnectionメソッドがトリガーされます。接続を受け入れる場合はServerSideConnectionオブジェクトを返し、拒否する場合はNULLを返します。いったん接続が許可されると、対応するTCPConnectionコールバックが開始され、他のクライアントと同じように接続を処理することができます。
新しい接続のリッスンを停止するには、call.ActiveSideConnectionを呼び出すだけです:
cs.ServerListener.me.stopListening()
注意:アクティブな接続は、手動で閉じるまで残ります。
統一されたクラス構造 = 簡素化されたコード
この設計の主な利点は、クライアント接続とサーバー接続の両方に同じTCPConnectionクラスが使われることです。この対称性により、実装が単純化され、コードの再利用が促進されます。
結論
4D v20 R9にTCPListenerクラスが追加されたことで、4Dで堅牢なTCPサーバーを作成できるようになりました。TCPConnectionと組み合わせることで、新しいツールは、双方向のTCP通信を扱うための完全なフレームワークを提供します。
質問やフィードバックがあれば、遠慮なく4Dフォーラムにお寄せください。