Tcpclient class in C # is very convenient to operate TCP connection, very good!
However, this class does not set timeout for the connect operation!
The default timeout value is 60 seconds, which is obviously too long.
We can use the thread join thread with the parameter to solve this problem. The following class is the tcpcliento class with the connection timeout parameter.
The tcpclientwithtimeout. CS class:
Using system; using system. net. Sockets; using system. Threading; // <summary> // tcpclientwithtimeout is used to set a class with the connection timeout function.
/// You can set the wait time-out time in milliseconds (1000 = 1 second) /// For example: // tcpclient connection = new tcpclientwithtimeout ('192, 127. 0.0.1 ', 80, 1000 ). connect (); // </Summary> public class tcpclientwithtimeout {protected string _ hostname; protected int _ port; protected int _ timeout_milliseconds; protected tcpclient connection; protected bool connected; protected exception; Public partition (string hostname, int port, int timeout_milliseconds) {_ hostname = hostname; _ Port = port; _ timeout_milliseconds = timeout_milliseconds;} public tcpclient connect () {// kick off the thread that tries to connect connected = false; Exception = NULL; thread = new thread (New threadstart (beginconnect); thread. isbackground = true; // process as a background thread
// It does not take too long for the machine
Thread. Start (); // wait for the following time
Thread. Join (_ timeout_milliseconds); If (connected = true) {// if it succeeds, the tcpclient object thread. Abort (); return connection ;}if (exception! = NULL) {// if it fails, an error thread will be thrown. abort (); throw exception;} else {// similarly throw the error thread. abort (); string message = string. format ("tcpclient connection to {0 }:{ 1} timed out", _ hostname, _ port); throw new timeoutexception (Message) ;}} protected void beginconnect () {try {connection = new tcpclient (_ hostname, _ port); // mark successful, return connected = true;} catch (exception ex) {// Mark failed exception = ex ;}}}
The following example shows how to connect a website to send 10 bytes of data and receive 10 bytes of data with a 5-second timeout.
// Connect with a 5 second timeout on the connection
Tcpclient connection = new tcpclientwithtimeout ("www.google.com", 80,500 0). Connect ();
Networkstream stream = connection. getstream ();
// Send 10 bytes
Byte [] to_send = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xa };
Stream. Write (to_send, 0, to_send.length );
// Receive 10 bytes
Byte [] readbuf = new byte [10]; // You must allocate space first
Stream. readtimeout = 10000; // 10 second timeout on the read
Stream. Read (readbuf, 0, 10); // read
// Disconnect nicely
Stream. Close (); // workaround for A. net bug: http://support.microsoft.com/kb/821625
Connection. Close ();