从服务器读取文件内容,然后通过套接字C将其发送到客户端#

时间:2010-11-08 18:56:06

标签: sockets file-io streamreader streamwriter

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

这是服务器

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";
        }

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

Sample code for StreamReader使用下面的结构来检测流的结束。另外 - 你真的想在那个循环中读两行吗?

while (reader.Peek() >= 0) 
{
    s= reader.ReadLine();
    textBox4.Text += s + Environment.NewLine + Environment.NewLine;
}

答案 2 :(得分:0)

您提到这是一个GUI应用程序?如果是这样,你正在阅读哪个帖子?如果您正在主线程上执行读取操作,那么应用程序消息循环将被冻结,并且在您停止另一方并终止连接之前不会显示任何内容。