Server と Client で通信

Cpp/CLI で TCP(Transmission Control Protocol) Server に Client から接続します。

前田稔の超初心者のプログラム入門

プログラムの説明

  1. .NET Frame Work を使うと「共通した API を使って自分の得意とする言語でアプリケーションを開発することが出来る」と言うのが Microsoft の宣伝文句です。
    そこで C/C++ と C# を使って同様の Network Application を作成してみました。
    第三弾は TCP Server に Client から接続して、メッセージを送信するアプリケーションです。
  2. Server 側のプログラムの手順です。
    Server はセッションを開設して Client からの接続を待ちます。
    1. ソケットを作る
    2. IP アドレスとポートを設定する
    3. 接続待ちする
    4. クライアントからの接続を受け付ける
    5. メッセージを受信する
  3. 空のプロジェクトから作成 を参考にプロジェクトを作成して下さい。
    Console.cpp をフォルダーに格納して、プロジェクトに追加して下さい。
    TCP Server 側の Console.cpp の全ソースコードです。
    /*★ Tcp Server Program    前田 稔 ★*/
    #using <System.dll>
    
    using namespace System;
    using namespace System::IO;
    using namespace System::Net;
    using namespace System::Net::Sockets;
    using namespace System::Text;
    using namespace System::Threading;
    void main()
    {
       try
       {
          // Set the TcpListener on port 13000.
          Int32 port = 13000;
          IPAddress^ localAddr = IPAddress::Parse( "127.0.0.1" );
    
          TcpListener^ server = gcnew TcpListener( localAddr,port );
    
          // Start listening for client requests.
          server->Start();
    
          // Buffer for reading data
          array^bytes = gcnew array(256);
          String^ data = nullptr;
    
          // Enter the listening loop.
          while ( true )
          {
             Console::Write( "Waiting for a connection... " );
    
             // Perform a blocking call to accept requests.
             // You could also user server.AcceptSocket() here.
             TcpClient^ client = server->AcceptTcpClient();
             Console::WriteLine( "Connected!" );
             data = nullptr;
    
             // Get a stream Object* for reading and writing
             NetworkStream^ stream = client->GetStream();
             Int32 i;
    
             // Loop to receive all the data sent by the client.
             while ( i = stream->Read( bytes, 0, bytes->Length ) )
             {
                // Translate data bytes to a UTF8 String*.
                data = Text::Encoding::UTF8->GetString( bytes, 0, i );
                Console::WriteLine( "Received: {0}", data );
    
                // Process the data sent by the client.
                data = data->ToUpper();
                array^msg = Text::Encoding::UTF8->GetBytes( data );
    
                // Send back a response.
                stream->Write( msg, 0, msg->Length );
                Console::WriteLine( "Sent: {0}", data );
             }
    
             // Shutdown and end connection
             client->Close();
          }
       }
       catch ( SocketException^ e ) 
       {
          Console::WriteLine( "SocketException: {0}", e );
       }
    
       Console::WriteLine( "\nHit enter to continue..." );
       Console::Read();
    }
    
  4. アプリケーションを特定するのに必要なポート番号とIPアドレスを設定して Client からの接続を待ち状態で待機します。
    詳しい説明は C# のページを参照して下さい。
  5. Client 側のプログラムの手順です。
    Client はセッションを開設している Server に接続してメッセージを送信します。
    1. ソケットを作る
    2. 接続相手を設定する
    3. 接続する
    4. メッセージを送信する
  6. 空のプロジェクトから作成 を参考にプロジェクトを作成して下さい。
    Console.cpp をフォルダーに格納して、プロジェクトに追加して下さい。
    Client 側の Console.cpp の全ソースコードです。
    /*★ Tcp Client Program    前田 稔 ★*/
    #using <System.dll>
    
    using namespace System;
    using namespace System::IO;
    using namespace System::Net;
    using namespace System::Net::Sockets;
    using namespace System::Text;
    using namespace System::Threading;
    
    void Connect( String^ server, String^ message )
    {
       try
       {
          // Create a TcpClient.
          Int32 port = 13000;
          TcpClient^ client = gcnew TcpClient( server,port );
    
          array^data = Text::Encoding::UTF8->GetBytes( message );
    
          // Get a client stream for reading and writing.
          NetworkStream^ stream = client->GetStream();
    
          // Send the message to the connected TcpServer. 
          stream->Write( data, 0, data->Length );
    
          Console::WriteLine( "Sent: {0}", message );
    
          // Buffer to store the response bytes.
          data = gcnew array(256);
    
          String^ responseData = String::Empty;
    
          // Read the first batch of the TcpServer response bytes.
          Int32 bytes = stream->Read( data, 0, data->Length );
          responseData = Text::Encoding::UTF8->GetString( data, 0, bytes );
          Console::WriteLine( "Received: {0}", responseData );
    
          // Close everything.
          client->Close();
       }
       catch ( ArgumentNullException^ e ) 
       {
          Console::WriteLine( "ArgumentNullException: {0}", e );
       }
       catch ( SocketException^ e ) 
       {
          Console::WriteLine( "SocketException: {0}", e );
       }
    
       Console::WriteLine( "\n Press Enter to continue..." );
       Console::Read();
    }
    
    void main()
    {
       //Connect("127.0.0.1", "Hello Network");
       Connect("127.0.0.1", "始めまして!");
    }
    
  7. 日本語(漢字)を送信するために UTF8 を使っています。
    送信する側も、受信する側も UTF8 を使って下さい。
    詳しい説明は C# のページを参照して下さい。
  8. プログラムのテストは次の手順で行って下さい。
    1. デバッグモードで Server を起動すると、メッセージを受信する状態で待機します。
    2. 続いて同じマシンで Client を起動します。
      メッセージが Server に送られて表示されます。
    3. Client はメッセージの送信が終わると終了確認を求めます。
      Enter で応答すると終了します。
    4. Client は何度でも起動して、メッセージを送ることが出来ます。
    5. Srever は強制的に終了(デバッグ/デバッグの停止)させて下さい。
  9. C# プログラムは「超初心者のプログラム入門(C#)」から Server と Client で通信 を参照して下さい。
    また、Win32 PAI を使ったプログラムも掲載しています。
    Server と Client で通信 を参照して下さい。
    パソコンがネットワークで接続されているか否かの確認は ping コマンドで行います。
    FTP サーバーを構築する を参照して下さい。
    最近では windows system やセキュリティソフトにより、ポートが閉じられている場合があります。
    通信が出来ないときは、コントロールパネルを開いて確認して下さい。

超初心者のプログラム入門(C/C++)