2012-02-21 12 views
-1

私はC#で単純なTCPクライアント/サーバーを作成していますが、問題があります。私がtelnetで自分のコードをテストすると、サーバはソケットの細工を読み込んで結果を書いています。しかし、私のクライアントがソケット上に文章を書くとき、サーバーはreadLine関数でブロックされます。readline()でTCPソケットをC#で読み込めません

ここでは、私のクライアントを持っている:

public Boolean initConnection(String ip) 
     { 
      try 
      { 
       this.client.Connect("127.0.0.1", 40000); 
       this.output = this.client.GetStream(); 
       this.reader = new StreamReader(this.output, Encoding.UTF8); 
       this.writer = new StreamWriter(this.output, Encoding.UTF8); 
       writer.Write("one sentence"); 
       return (true); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
       return (false); 
      } 
     } 

、ここであなたは私のサーバーを持っている:

class SNetwork 
    { 
     private Thread Tread; 
     private TcpListener server; 
     private TcpClient client; 
     private StreamReader reader; 
     private StreamWriter writer; 
     private NetworkStream output; 
     private State state; 

     public void initReading() 
     { 
      this.server = new TcpListener(IPAddress.Any, 40000); 
      output = client.GetStream(); 
      reader = new StreamReader(output, Encoding.UTF8); 
      writer = new StreamWriter(output, Encoding.UTF8); 
      this.Tread = new Thread(new ThreadStart(this.read)); // this.Tread is a thread 
      this.Tread.Start(); 
     } 

    private void read() 
     { 
      try 
      { 
       while (Thread.CurrentThread.IsAlive) 
       { 
        String result; 

        if (this.client.Client.Poll(10, SelectMode.SelectRead)) 
        { 
         this.state = State.Closed; 
         break; 
        } 
        else 
        { 
         result = reader.ReadLine(); 
         if (result != null && result.Length > 0) 
          Console.WriteLine(result); 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
      } 
     } 
} 

誰でもplzは私を助けることができますか?私は解決策

+0

'writer.WriteLine( "一文")を試してみてください;' –

答えて

1

にこのコードを見つけることができません:

writer.Write("one sentence"); 

は、ラインターミネータを書いていない - ので、あなたのサーバーコードを使用すると、行を終了したことを知りません。 WriteLineに変更し(ライターをフラッシュしてください)、それは問題ありません。

あなたは常にTCP/IPがストリームベースのプロトコルであることを心に留めてする必要があります - あなたはWrite呼び出しを発行し、そしてあなたの場合」とは、サーバーはできるだけ多くRead呼び出しでデータを受け取ることを期待することはできません上に回線終端プロトコルがある場合は、回線を終端する必要があります。

は(別の問題として、.NETの命名規則に従うことが良いでしょう...)

+0

ARF。これに感謝します。それはうまく動作します! –

関連する問題