C# 給TcpClient的Connect方法設置超時時間TimeOut

C# 給TcpClient的Connect方法設置超時時間TimeOut

C# 給TcpClient的Connect方法設置超時時間TimeOut


資料來源: https://www.cnblogs.com/xyz0835/p/10179665.html


GITHUB: https://github.com/jash-git/CS_test_jint-project



01.Net 4.5之前Code:

var client = new TcpClient();
var result = client.BeginConnect( " remotehost " , this .Port, null , null );

var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds( 1 ));

if (! success)
{
    throw  new Exception( " Failed to connect. " );
}

// we have connected 
client.EndConnect(result);


02.Net 4.5之後Code:

var client = new TcpClient();
if (!client.ConnectAsync( " remotehost " , remotePort).Wait( 1000 ))
{
    // connection failure 
}


03.自己實測(4.5可用):

TcpClient tcpSocket = new TcpClient();
tcpSocket.ReceiveBufferSize = 8192;//8k
tcpSocket.SendBufferSize = 8192;//8k
int intTcpRetryCount = 0;
try
{
	do
	{
		//tcpSocket.Connect("192.168.1.54", 9100);
		if (!tcpSocket.ConnectAsync("192.168.1.54", 9100).Wait(1000))//if (!tcpSocket.Connected)
		{
			tcpSocket = null;
			tcpSocket = new TcpClient();
			intTcpRetryCount++;
		}
		else
		{
			break;
		}
	}while ((!tcpSocket.Connected) && (intTcpRetryCount<3));
	
	if(tcpSocket.Connected)
	{
		if ((ESCPOSCommand != null) && (ESCPOSCommand.value != null))
		{
			for (int i = 0; i < ESCPOSCommand.value.Count; i++)
			{
				byte[] bytes = Encoding.GetEncoding("big5").GetBytes(ESCPOSCommand.value[i]);
				NetworkStream tcpStream = tcpSocket.GetStream();
				tcpStream.Write(bytes, 0, bytes.Length);
				tcpStream.Flush();
			}
		}
		tcpSocket.GetStream().Close();
		tcpSocket.Close();
	}
	else
	{

	}

}
catch (Win32Exception ex)
{

}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *