我想使用 StreamReader 和 StreamWriter 通过 TCPClient.NetworkStream 接收和发送数据。代码如下图所示:
客户端代码:
using (TcpClient client = new TcpClient())
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9001);
client.Connect(localEndPoint);
client.NoDelay = true;
using(NetworkStream stream = client.GetStream())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
using (StreamReader reader = new StreamReader(stream))
{
string message = "Client says: Hello";
writer.WriteLine(message);
// If I comment the line below, the server receives the first message
// otherwise it keeps waiting for data
string response = reader.ReadToEnd();
Console.WriteLine(response);
}
;
}
}
}
注意:如果我评论 reader.ReadToEnd(); 然后服务器接收到消息,否则服务器一直等待来自客户端的数据。ReadToEnd 是问题吗?
服务器代码异步接受连接,但以同步方式处理数据:
class Program
{
private static AsyncCallback tcpClientCallback;
static void Main(string[] args){
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9001);
TcpListener listener = new TcpListener(localEndPoint);
listener.Start();
tcpClientCallback = new AsyncCallback(ConnectCallback);
AcceptConnectionsAysnc(listener);
Console.WriteLine("Started Aysnc TCP listener, press any key to exit (server is free to do other tasks)");
Console.ReadLine();
}
private static void AcceptConnectionsAysnc(TcpListener listener)
{
listener.BeginAcceptTcpClient(tcpClientCallback, listener);
}
static void ConnectCallback(IAsyncResult result)
{
Console.WriteLine("Received a conenct request");
TcpListener listener = (TcpListener)result.AsyncState;
// We are starting a thread which waits to receive the data
// This is not exactly scalable
Task recieveTask = new Task(() => { HandleRecieve(result, listener); });
recieveTask.Start();
AcceptConnectionsAysnc(listener);
}
// This makes a blocking call - that means until the client is ready to
// send some data the server waits
private static void HandleRecieve(IAsyncResult result, TcpListener listener)
{
Console.WriteLine("Waiting for data");
using (TcpClient client = listener.EndAcceptTcpClient(result))
{
client.NoDelay = true;
using (NetworkStream stream = client.GetStream())
{
using (StreamReader reader = new StreamReader(stream))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
Stopwatch watch = new Stopwatch();
watch.Start();
string data = reader.ReadToEnd();
watch.Stop();
Console.WriteLine("Time: " + watch.Elapsed.TotalSeconds);
Console.WriteLine(data);
// Send a response to client
writer.WriteLine("Response: " + data);
}
}
}
}
}
}