3.6.2 TCP/IP通信機能を使用する場合のコーディング例(C#の場合)

TCP/IP通信機能を使用する場合の,ASP.NET Webアプリケーションでの使用例を次に示します。

コメント中の(1),(2)などは「3.6.1 TCP/IP通信機能を使用する場合のメソッド発行手順」の説明の番号に対応しています。

using System;
using Hitachi.OpenTP1;
using Hitachi.OpenTP1.Connector;
using MyCompany;

namespace MyCompany
{
 public class MyForm1 : System.Web.UI.Page
 {
   …
   private void Button1_Click(object sender, System.EventArgs e)
   {
     // このボタンがクリックされたら
     //  OpenTP1<ServerA>のサービス要求を行う
     // グローバル変数のアプリケーション状態から
     //  TP1ConnectionManagerを取得する
     // (1) TP1ConnectionManagerクラスの生成
     TP1ConnectionManager tcm =
        (TP1ConnectionManager)this.Application["tcmServerA"];
     // (2) TcpipConnectionオブジェクトの取得
     tc = tcm.GetTcpipConnection();
     try {
       Encoding enc = Encoding.Default;
       // (3) TcpipInfoクラスの生成
       TcpipInfo info = new TcpipInfo();
       // (4) 通信形態
       info.Flags = TcpipInfo.TCPIP_SENDRECV;
       // (4) 最大応答待ち時間
       info.WatchTime = 180;
       // (5) 入力用インデクスドレコードの生成
       IndexedRecord input =
                     tcm.CreateIndexedRecord("in_record");
       // (6) 入力データの設定
       string indata = "Say Hello to OpenTP1!";
       // (6) 入力データの設定
       input.Add(enc.GetBytes(indata));
       // (7) 出力用インデクスドレコードの生成
       IndexedRecord output =
                     tcm.CreateIndexedRecord("out_record");
       // (8) 出力データ用領域の設定
       output.Add(new byte[this.textBox1.MaxLength*2]);
       // (9) TCP/IP通信の実行
       bool ret = tc.Execute(info, input, output);
       // (10) データの取り出し
       byte[] outBuf = (byte[])output[0];
       // (10) データの取り出し
       this.textBox1.Text = enc.GetString(outBuf);
     } catch (TP1ConnectorException exp) {
       // Connector .NETが検知したエラー
     } catch (TP1Exception exp) {
       // Connector .NET(OpenTP1共通クラス)が検知したエラー
     } catch (Exception exp) {
       // 予期しない例外
     }
     finally
     {
       // (11) コネクションをコネクションプールに戻す
       if (tc != null) tc.Dispose();
     }
   }
 }
}