I am trying to do a simple TCP application that will send a request to a server and after that will receive a PDF file which it should process and save to the PC. I have done some research already on this thing but all I come up with is either a program that always listens to some address and port so it can receive a file, or a program that send a request then receives a small response, not a stream. For now I have the following code:
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());
}
}
So my code should at first send a hash to the server when I press a button, then receive the file as a response. The thing I am trying to do is to somehow combine the button1_Click method and the sendRequest() method, but I've found no way to do it. Thank you.