2009-04-03 14 views
0

私はクライアント/サーバを書いています。サーバーはクライアントにデータを送信します。しかし、クライアントは、一度接続すれば、接続が終了した後で再び接続しようとすることはありません。同様に、サーバーからメッセージが送信されると、今後の接続の試行は無視されます。クライアント/サーバは1つの接続の後で両方をあきらめます

サーバー:

public Server(String p) 
    { 
     path = p; 
     listener = new TcpListener(IPAddress.Any, 1337); 
     listener.Start(); 
     Thread t = new Thread(new ThreadStart(ListenForClients)); 
     t.IsBackground = true; 
     t.Start(); 
    } 

    private void ListenForClients() 
    { 
     TcpClient client = listener.AcceptTcpClient(); 
     new Thread(new ParameterizedThreadStart(HandleClientCom)).Start(client); 
    } 

    private void HandleClientCom(object TcpClient) 
    { 
     new Dialog("Connection", "Connection established."); 
     TcpClient client = (TcpClient)TcpClient; 
     NetworkStream stream = client.GetStream(); 
     //SslStream stream = new SslStream(client.GetStream()); 
     //stream.AuthenticateAsServer(new X509Certificate(path + "\\ServerCert.cer")); 

     ASCIIEncoding encoder = new ASCIIEncoding(); 
     String str = "This is a long piece of text to send to the client."; 
     byte[] bytes = encoder.GetBytes(str); 

     stream.Write(bytes, 0, bytes.Length); 
     stream.Flush(); 
    } 

クライアント:コードの膨大な量のため

public TCP(BackgroundWorker b) 
    { 
     try 
     { 
      bw = b; 
      client = new TcpClient(); 
      IPEndPoint server = new IPEndPoint(IPAddress.Parse(srv), 1337); 
      client.Connect(server); //Connect to the server 
      bw.ReportProgress(0); //Update the GUI with the connection status 

      Thread t = new Thread(new ParameterizedThreadStart(HandleComms)); 
      t.IsBackground = true; 
      t.Start(client); 
     } 
     catch (Exception ex) 
     { 
      lastException = ex; 
     } 
    } 

    public void HandleComms(object c) 
    { 
     Boolean keepListening = true; 
     TcpClient client = (TcpClient)c; 
     NetworkStream stream = client.GetStream(); 
     //stream = new SslStream(client.GetStream()); 
     //stream.AuthenticateAsClient(srv); 

     byte[] msg = new byte[4096]; ; 
     int bytesRead = 0; 

     while (keepListening) 
     { 
      try 
      { 
       bytesRead = stream.Read(msg, 0, 4096); 
      } 
      catch (Exception ex) 
      { 
       lastException = ex; 
      } 

      if (bytesRead > 0) 
      { 
       StreamWriter writer = new StreamWriter("C:\\Users\\Chris\\Desktop\\ClientLog.txt"); 
       ASCIIEncoding encoder = new ASCIIEncoding(); 
       rx = encoder.GetString(msg); 
       writer.WriteLine(rx); 
       keepListening = false; 
       writer.Close(); 
      } 
     } 
    } 

申し訳ありません。とにかく、どこが間違っているかを指摘できますか?

答えて

2

接続を受け入れたら、もう一度リスニングを開始する必要があります。

private void ListenForClients() 
{ 
    while(true) 
    { 
     TcpClient client = listener.AcceptTcpClient(); 
     new Thread(new ParameterizedThreadStart(HandleClientCom)).Start(client); 
    } 
} 
+0

絶対に上のスポット:

は、ちょうどこの変更を作ってみましょう! – Bailz

関連する問題