Reputation: 13
How can i send multiple files between a client and a server in c# parallely. I have already tried to send single file ,the code is given below.
And also please explain difference between sending a file without using socket(as done below) and using socket to send a file
SERVER SIDE
TcpListener filelistener = new TcpListener(IPAddress.Parse(GetIP()), 8085);
MessageBox.Show("server started");
filelistener.Start();
TcpClient client = filelistener.AcceptTcpClient();
Message("Client connection accepted from :" + client.Client.RemoteEndPoint + ".");
byte[] buffer = new byte[1500];
int bytesread = 1;
StreamWriter writer = new StreamWriter("C:\\Users\\ab\\Desktop\\abc.txt");
while (bytesread > 0)
{
bytesread = client.GetStream().Read(buffer, 0, buffer.Length);
if (bytesread == 0)
break;
writer.BaseStream.Write(buffer, 0, buffer.Length);
Message(bytesread + " Received. ");
}
writer.Close();
CLIENT SIDE
try
{
StreamReader sr = new StreamReader(textBox1.Text);
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(new IPEndPoint(IPAddress.Parse(GetIP()), 8085));
byte[] buffer = new byte[1500];
long bytesSent = 0;
while (bytesSent < sr.BaseStream.Length)
{
int bytesRead = sr.BaseStream.Read(buffer, 0, 1500);
tcpClient.GetStream().Write(buffer, 0, bytesRead);
Message(bytesRead + " bytes sent.");
bytesSent += bytesRead;
}
tcpClient.Close();
MessageBox.Show("finished");
Console.ReadLine();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Upvotes: 1
Views: 1465
Reputation: 55720
The TCPClient and TCPListener that both use sockets internally and simply provide a higher level of abstraction. In other words, you are still using sockets, just not directly.
In order to send multiple files in parallel, you will need the server to be able to accept more than one connection. There are several ways you can accomplish this but the general idea is the same:
On the client, you can spin up a number of TCPClient objects, one for each file you'd like to send and send the data to your listener.
You will have to figure out the logistics (the protocol) of your data transfers. As you get the incoming data transfer for each file you are receiving on the listener side, you have to decide what each file represents and who it is from. The details here are quite subjective and not really a good fit for StackOverflow Q&A.
Upvotes: 1