Sockets and Threads
-
I'm working on an FTP client, and using sockets to receive data from a server. When the server sends any data back to the application, I have to wait before the application repsonds. I'd like to starts the transfer for the data in a new thread if possible, leaving the rest of the app free to respond to the user and not just show an hourglass. Is this possible? I'm unsure how to get the data back from the thread.
Socket socket = openSocket(); SendCommand("MLSD"); if(statusCode != 125 && statusCode != 150) { LogText = "Error opening connection\n"; return; } DateTime timeOutDate = DateTime.Now.AddSeconds(timeOut); bldBuffer.Remove(0, bldBuffer.Length); while(DateTime.Now < timeOutDate) { int bytes = socket.Receive(buffer, buffer.Length, 0); bldBuffer.Append(Encoding.ASCII.GetString(buffer, 0, bytes)); if(bytes < buffer.Length) { // there weren't enough bytes to fill the buffer, so the stream is finished break; } } socket.Close();
OpenSocket() creates a new socket to the server, and SendCommand() send the specified command over the control connection. The application works, it's just that I have to wait for it to respond. Thanks for any input. -
I'm working on an FTP client, and using sockets to receive data from a server. When the server sends any data back to the application, I have to wait before the application repsonds. I'd like to starts the transfer for the data in a new thread if possible, leaving the rest of the app free to respond to the user and not just show an hourglass. Is this possible? I'm unsure how to get the data back from the thread.
Socket socket = openSocket(); SendCommand("MLSD"); if(statusCode != 125 && statusCode != 150) { LogText = "Error opening connection\n"; return; } DateTime timeOutDate = DateTime.Now.AddSeconds(timeOut); bldBuffer.Remove(0, bldBuffer.Length); while(DateTime.Now < timeOutDate) { int bytes = socket.Receive(buffer, buffer.Length, 0); bldBuffer.Append(Encoding.ASCII.GetString(buffer, 0, bytes)); if(bytes < buffer.Length) { // there weren't enough bytes to fill the buffer, so the stream is finished break; } } socket.Close();
OpenSocket() creates a new socket to the server, and SendCommand() send the specified command over the control connection. The application works, it's just that I have to wait for it to respond. Thanks for any input.Is there some reason you are not using the classes in System.Net namespace that implement the FTP protocol?
Echilon wrote:
I'd like to starts the transfer for the data in a new thread if possible
Look at the BackgroundWorker or something. It's in the toolbox you can just drop it on your form. There now you are all prepared to do multi-threaded development. :rolleyes:
led mike