我在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?我沒有找到一個解決方案
試着用'writer.WriteLine( 「一句」);' – 2012-02-21 17:06:45