我正在使用Tcp套接字和流读取器/写入器编写基本的客户端和服务器程序。我的客户端和服务器连接正常,可以使用StreamWriter和StreamReader.ReadLine()发送单行消息;但是,当我希望读取多行时,我的循环会冻结,并且永远不会继续执行其余的代码。
客户端:
TcpClient client = new TcpClient();
client.Connect(hostname, port);
StreamWriter sw = new StreamWriter(client.GetStream());
StreamReader sr = new StreamReader(client.GetStream());
sw.WriteLine("PUT /" + name + "\r\n" + "nextline" + "\r\n" + "moreline" + "\r\n");
sw.Flush(); //eventually used for http style request
Console.WriteLine(sr.ReadToEnd());
服务器:
static void runServer()
{
TcpListener listener;
Socket connection;
NetworkStream socketStream;
try
{
listener = new TcpListener(IPAddress.Any, 43);
listener.Start();
Console.WriteLine("Server Listening...");
while (true)
{
connection = listener.AcceptSocket();
socketStream = new NetworkStream(connection);
Console.WriteLine("Connection Received...");
doRequest(socketStream);
socketStream.Close();
connection.Close();
}
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void doRequest(NetworkStream socketStream)
{
try
{
StreamWriter sw = new StreamWriter(socketStream);
StreamReader sr = new StreamReader(socketStream);
String line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
sw.WriteLine("Success");
sw.Flush();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
输出:
Server Listening...
Connection Recieved...
PUT /dave
nextline
moreline
但是程序不会执行sw.WriteLine(“Success”),sw.Flush()或任何Console.WriteLine()。 我尝试的任何其他方法只在第一行读取,然后客户端收到“成功消息”,服务器继续它应该。
感谢任何帮助!
编辑:只是为了澄清,我只希望将这一个WriteLine()从我的客户端发送到服务器,但是我希望将这些行分开,以便我可以将正确的数据从我的服务器发送回客户端。