ローカルPOP3サーバを作る(その2)

調べてみると.NETの方が簡単そうだったので実験してみた。実験なのでコピペしただけのコードだ。

void Pop3S::ttest_tcp(void)
{
  try {
    // Set the TcpListener on port 13000.
    int port = 12345;
    IPAddress^ localAddr = IPAddress::Parse( "127.0.0.1" );
    // TcpListener* server = new TcpListener(port);
    TcpListener^ server = gcnew TcpListener(localAddr,port );
    // Start listening for client requests.
    server->Start();
    // Buffer for reading data
    array<Byte>^bytes = gcnew array<Byte>(256);
    String^ data = nullptr;
    // Enter the listening loop.
    while ( true )
    {
      System::Diagnostics::Debug::Write( "Waiting for a connection... " );
      // Perform a blocking call to accept requests.
      // You could also user server.AcceptSocket() here.
      TcpClient^ client = server->AcceptTcpClient();
      System::Diagnostics::Debug::WriteLine( "Connected!" );
      data = nullptr;
      // Get a stream Object* for reading and writing
      NetworkStream^ stream = client->GetStream();
      int i;
      // Loop to receive all the data sent by the client.
//         while ( i = stream->Read( bytes, 0, bytes->Length ) )
      i = stream->Read(bytes, 0, bytes->Length);
      {
        // Translate data bytes to a ASCII String*.
        data = Text::Encoding::ASCII->GetString( bytes, 0, i );
        Console::WriteLine( "Received: {0}", data );
        // Process the data sent by the client.
        data = "HELLO:" + data->ToUpper();
        array<Byte>^msg = Text::Encoding::ASCII->GetBytes( data );
        // Send back a response.
        stream->Write( msg, 0, msg->Length );
      }
      // Shutdown and end connection
      client->Close();
    }
  } catch ( SocketException^ e ) {
    System::Diagnostics::Debug::Write( e->Message );
  }finally {
    System::Diagnostics::Debug::Write("koko");
  }
}

AcceptTcpClient()で接続要求待ちになってしまうので、スレッドで動かした。実験してみた限り、良さそうなのでこの方法を使うことにした。ちなみに実験コードなので、動作した後の処理はメチャメチャなのは自覚しています。

private:
   Pop3S^ pop3s;
   Thread^ oThread;
private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
            pop3s = gcnew Pop3S();
            oThread = gcnew Thread( gcnew ThreadStart(pop3s, &Pop3S::ttest_tcp ) );
            oThread->Start();
         }
private: System::Void end_Click(System::Object^  sender, System::EventArgs^  e) {
            oThread->Abort();
            this->Close();
         }