I am trying to create a server that will receive files sent by clients over the network. If the client decides to send one file at a time, there is no problem, I get the file as I expected, but if it tries to send more than one, I get only the first.
Here's the server code: I use one thread for each connected client
public void ProcessClients() { while (IsListening) { ClientHandler clientHandler = new ClientHandler(listener.AcceptTcpClient()); Thread thread = new Thread(new ThreadStart(clientHandler.Process)); thread.Start(); } }
The following code is part of the ClientHandler class
public void Process() { while (client.Connected) { using (MemoryStream memStream = new MemoryStream()) { int read; while ((read = client.GetStream().Read(buffer, 0, buffer.Length)) > 0) { memStream.Write(buffer, 0, read); } if (memStream.Length > 0) { Packet receivedPacket = (Packet)Tools.Deserialize(memStream.ToArray()); File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Guid.NewGuid() + receivedPacket.Filename), receivedPacket.Content); } } } }
At the first iteration, I get the first file sent, but after that I get nothing. I tried using Thread.Sleep (1000) at the end of each iteration with no luck.
On the other hand, I have this code (for clients)
. . client.Connect(); foreach (var oneFilename in fileList) client.Upload(oneFilename); client.Disconnect(); . .
Upload Method:
public void Upload(string filename) { FileInfo fileInfo = new FileInfo(filename); Packet packet = new Packet() { Filename = fileInfo.Name, Content = File.ReadAllBytes(filename) }; byte[] serializedPacket = Tools.Serialize(packet); netStream.Write(serializedPacket, 0, serializedPacket.Length); netStream.Flush(); }
netStream (NetworkStream) opens when connected and closes when disconnected.
Where is the black hole? Can I send multiple objects as I try to do?
Thank you for your time.