C#:发送TCP请求,然后接收大文件流作为响应

时间:2019-01-14 21:31:42

标签: c# tcpclient

我正在尝试做一个简单的TCP应用程序,它将向服务器发送一个请求,然后将收到一个PDF文件,该文件应处理并保存到PC。我已经对此进行了一些研究,但我想出的只是一个总是侦听某个地址和端口以便可以接收文件的程序,或者是一个发送请求然后接收到很小响应的程序,而不是流。现在,我有以下代码:

    private void button1_Click(object sender, EventArgs e)
    {
        string fileHash = hashLabel.Text;
        IPAddress localAddr = IPAddress.Parse("127.0.0.1");
        var listener = new TcpListener(localAddr, 11000);
        listener.Start();
        while (true)
        {
            using (var client = listener.AcceptTcpClient())
            using (var stream = client.GetStream())
            using (var output = File.Create("receivedFile.pdf"))
            {
                Console.WriteLine("Client connected. Starting to receive the file");

                // read the file in chunks of 1KB
                var buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, bytesRead);
                }
            }
        }
    }

    private void sendRequest(string fileHash)
    {
        try
        {
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Loopback, 11000);

            Socket serverSender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                serverSender.Connect(remoteEP);

                Console.WriteLine("Socket connected to {0}", serverSender.RemoteEndPoint.ToString());

                byte[] msg = Encoding.ASCII.GetBytes(fileHash);
                int bytesSent = serverSender.Send(msg);

                serverSender.Shutdown(SocketShutdown.Both);
                serverSender.Close();

            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception ex2)
            {
                Console.WriteLine("Unexpected exception : {0}", ex2.ToString());
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

因此,当我按下按钮时,我的代码应首先将哈希发送到服务器,然后将文件作为响应接收。我正在尝试做的事情是以某种方式组合button1_Click方法和sendRequest()方法,但我发现没有办法做到这一点。谢谢。

0 个答案:

没有答案