0

我在这里尝试通过服务器发送文本文件的内容并将其发送给客户端

这是服务器

Socket server = new Socket(AddressFamily.InterNetwork,
                 SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 9050);
        server.Bind(localEP);
        server.Listen(10);
        Console.WriteLine("Waiting for Client...");
        Socket client = server.Accept();
        IPAddress clientAddress = ((IPEndPoint)client.RemoteEndPoint).Address;
        Console.WriteLine("Got connection from " + clientAddress);

    NetworkStream stream = new NetworkStream(client); 
    StreamReader reader = new StreamReader(stream);
    StreamWriter writer = new StreamWriter(stream);


    writer.WriteLine("Welcome to my test server");
    writer.Flush();
    string line = null;
    while ((line = reader.ReadLine()).Length != 0)
    {
        Console.WriteLine("loooking for this file:" + line);
        System.IO.FileInfo fi = new System.IO.FileInfo(line);
        Console.WriteLine("Found");
        writer.WriteLine("File Size: " + fi.Length + "\nContent:");
        StreamReader tr = new StreamReader(line);
        string s = null;
        //string b = "";
    while((s= tr.ReadLine()).Length != 0)
        {
            writer.WriteLine(tr.ReadLine());
            writer.Flush();
        }

        tr.Close();

    }
    client.Close(); server.Close();

它从服务器读取的客户端部分是这个

String line = null;
        line = textBox3.Text;
        writer.WriteLine(line);   // Send line to Server
        writer.Flush();
        string s = null;
        // Read line from server, then echo on the screen 
        while((s= reader.ReadLine()).Length != 0)
        {
            textBox4.Text += reader.ReadLine() + "\r\n\r\n";
        }

当我运行代码时,完全没有错误,但是客户端卡住了,当我停止服务器时,文件的内容将显示,,,顺便说一句,它是一个 GUI 应用程序

4

3 回答 3

0

while ((s = reader.ReadLine()) != null) { textBox4.Text += s; }

于 2010-11-08T19:00:17.837 回答
0

StreamReader 的示例代码使用下面的构造来检测流的结束。另外——你真的想在那个循环中读两行吗?

while (reader.Peek() >= 0) 
{
    s= reader.ReadLine();
    textBox4.Text += s + Environment.NewLine + Environment.NewLine;
}
于 2010-11-08T19:11:08.867 回答
0

你提到这是一个 GUI 应用程序?如果是这样,您在哪个线程上阅读?如果您在主线程上进行读取,则应用程序消息循环将被冻结,并且在您停止另一端并终止连接之前什么都不会显示。

于 2010-11-08T20:42:49.507 回答