2012-02-21 73 views
-1

我在C#中使一個簡單的TCP客戶端/服務器,我有問題。當我用telnet測試我的代碼時,服務器正在讀取插口並記錄結果。但是,當我的客戶端在套接字上寫入一個句子時,服務器在readLine函數中被阻塞。無法讀取在c#中的TCP套接字與readline()

這裏有我的客戶:

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( 「一句」);' – 2012-02-21 17:06:45

回答

1

此代碼:

writer.Write("one sentence"); 

不寫一行終結 - 讓你的服務器代碼不知道你已經完成了線。將其更改爲WriteLine(並刷新作者)應該沒問題。

你總是需要牢記的是TCP/IP是一個基於流協議 - 你不能指望服務器爲您開具Write電話與許多Read調用接收數據,如果你」在上面的行終止協議,你需要確保你終止你的線路。

(作爲一個獨立的問題,它是仿效.NET命名約定是個好主意......)

+0

ARF。感謝這一點。它工作正常! – 2012-02-21 17:26:15