Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sockets and Threads

Status
Not open for further replies.

Echilon

Programmer
Feb 22, 2007
54
GB
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.
Code:
			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.
 
Yes, you can start the socket in a new thread. I don't have any code with me atm...but check out the BeginReceive method. It uses non-blocking connections.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top