我正在尝试在两台计算机之间发送消息。我已经能够建立连接,但由于某些奇怪的原因,我无法获取流。
服务器代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace chat_server
{
class Program
{
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Any, 9999);
server.Start();
Console.WriteLine("Waiting for client connections");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client request accepted");
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);
Console.WriteLine("The message is " + reader.ReadToEnd());
}
}
}
客户代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace chat_client
{
class Program
{
static void Main(string[] args)
{
TcpClient client = new TcpClient("localhost", 9999);
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);
writer.Write("Hello world");
Console.WriteLine("Message Sent");
Console.ReadKey();
}
}
}
我的服务器代码通过打印接受的客户端请求来确认客户端连接。但是由于某种原因,我无法从流中获取数据。快速帮助将不胜感激。
谢谢