在C 中帶連線超時功能的TcpClient類

2021-07-13 11:29:03 字數 1476 閱讀 1444

關於tcpclient 類在c#中對於操作tcp connection是非常方便的,非常地好!

但是有一點就是,這個類對於connect操作沒有設定超時!

系統預設的是60秒的超時,這明顯過於地長。

我們可以重新去用thread的join這個帶引數的執行緒,來解決這個問題,下面的這個類就是但連線超時引數的tcpcliento類

using system;

using system.net.sockets;

using system.threading;

/// /// tcpclientwithtimeout 用來設定乙個帶連線超時功能的類

/// 使用者可以設定毫秒級的等待超時時間 (1000=1second)

/// 例如:

/// tcpclient connection = new tcpclientwithtimeout('127.0.0.1',80,1000).connect();

///

public class tcpclientwithtimeout

public tcpclient connect()

if (exception != null)

else

: timed out",

_hostname, _port);

throw new timeoutexception(message);

}} protected void beginconnect()

catch (exception ex)

}}下面的這個例子就是如何利用5秒的超時,去連線乙個**傳送10位元組的資料,並且接收10位元組的資料。

// connect with a 5 second timeout on the connection

tcpclient connection = new tcpclientwithtimeout("www.google.com", 80, 5000).connect();

networkstream stream = connection.getstream();

// send 10 bytes

byte to_send = ;

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:

connection.close();

對於tnsping的連線超時的功能補充

tnsping,作為oracle連線測試的乙個小巧的工具,其實大家已經不陌生了,但是使用tnsping有乙個問題,就是連線超時,當然這個和網路的安全策略等密不可分,但是擺在我面前的乙個問題是,現在有大量的伺服器,每台資料庫伺服器上都有tnsnames.ora,如果需要判斷tnsnames.ora裡面...

在C 中實現列印功能

在.net中可以很方便的實現列印功能。通常可以建立 printdocument 類的例項,設定描述列印方式的屬性,然後呼叫 print 方法開始列印程序。通過使用 printpageeventargs 中包含的 graphics 來處理用於指定列印輸出的 printpage 事件。具體 public...

在C 中實現DateDiff功能

且看它在vb.net中的定義 返回 variant long 的值,表示兩個指定日期間的時間間隔數目。datediff interval,date1,date2 firstdayofweek firstweekofyear datediff 函式語法中有下列命名引數 部分 描述 interval 必...