本文整理汇总了C#中System.Net.Sockets.TcpClient.EndConnect方法的典型用法代码示例。如果您正苦于以下问题:C# TcpClient.EndConnect方法的具体用法?C# TcpClient.EndConnect怎么用?C# TcpClient.EndConnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.TcpClient
的用法示例。
在下文中一共展示了TcpClient.EndConnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Ping
public static bool Ping(string host, int port, TimeSpan timeout, out TimeSpan elapsed)
{
using (TcpClient tcp = new TcpClient())
{
DateTime start = DateTime.Now;
IAsyncResult result = tcp.BeginConnect(host, port, null, null);
WaitHandle wait = result.AsyncWaitHandle;
bool ok = true;
try
{
if (!result.AsyncWaitHandle.WaitOne(timeout, false))
{
tcp.Close();
ok = false;
}
tcp.EndConnect(result);
}
catch
{
ok = false;
}
finally
{
wait.Close();
}
DateTime stop = DateTime.Now;
elapsed = stop.Subtract(start);
return ok;
}
}
示例2: IsDomainAlive
//This method uses TCPClient to check the validity of the domain name and returns true if domain exists, and false if it doesn't
private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
System.Uri uri = new Uri(aDomain);
string uriWithoutScheme = uri.Host.TrimEnd('/');
try
{
using (TcpClient client = new TcpClient())
{
var result = client.BeginConnect(uriWithoutScheme, 80, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));
if (!success)
{
// Console.Write(aDomain + " ---- No such domain exists\n");
return false;
}
// we have connected
client.EndConnect(result);
return true;
}
}
catch (Exception ex)
{
// Console.Write(aDomain + " ---- " + ex.Message + "\n");
}
return false;
}
示例3: Connect
public void Connect()
{
try
{
Close();
}
catch (Exception) { }
client = new TcpClient();
client.NoDelay = true;
IAsyncResult ar = client.BeginConnect(Host, Port, null, null);
System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
try
{
if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
{
client.Close();
throw new IOException("Connection timoeut.", new TimeoutException());
}
client.EndConnect(ar);
}
finally
{
wh.Close();
}
stream = client.GetStream();
stream.ReadTimeout = 10000;
stream.WriteTimeout = 10000;
}
示例4: Connect
/// <summary>
/// Begins the connection process to the server, including the sending of a handshake once connected.
/// </summary>
public void Connect()
{
try {
BaseSock = new TcpClient();
var ar = BaseSock.BeginConnect(ClientBot.Ip, ClientBot.Port, null, null);
using (ar.AsyncWaitHandle) {
if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) {
BaseSock.Close();
ClientBot.RaiseErrorMessage("Failed to connect: Timeout.");
return;
}
BaseSock.EndConnect(ar);
}
} catch (Exception e) {
ClientBot.RaiseErrorMessage("Failed to connect: " + e.Message);
return;
}
ClientBot.RaiseInfoMessage("Connected to server.");
BaseStream = BaseSock.GetStream();
WSock = new ClassicWrapped.ClassicWrapped {_Stream = BaseStream};
DoHandshake();
_handler = new Thread(Handle);
_handler.Start();
_timeoutHandler = new Thread(Timeout);
_timeoutHandler.Start();
}
示例5: IsPortOpen
private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout)
{
bool portIsOpen = false;
using (var tcp = new TcpClient())
{
IAsyncResult ar = tcp.BeginConnect(ipAddress, currentPort, null, null);
using (ar.AsyncWaitHandle)
{
//Wait connectTimeout ms for connection.
if (ar.AsyncWaitHandle.WaitOne(connectTimeout, false))
{
try
{
tcp.EndConnect(ar);
portIsOpen = true;
//Connect was successful.
}
catch
{
//Server refused the connection.
}
}
}
}
return portIsOpen;
}
示例6: Connect
public Boolean Connect(IPAddress hostAddr, Int32 hostPort, Int32 timeout)
{
// Create new instance of TCP client
_Client = new TcpClient();
var result = _Client.BeginConnect(hostAddr, hostPort, null, null);
_TransmitThread = null;
result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout));
if (!_Client.Connected)
{
return false;
}
// We have connected
_Client.EndConnect(result);
EventHandler handler = OnConnected;
if(handler != null)
{
handler(this, EventArgs.Empty);
}
// Now we are connected --> start async read operation.
NetworkStream networkStream = _Client.GetStream();
byte[] buffer = new byte[_Client.ReceiveBufferSize];
networkStream.BeginRead(buffer, 0, buffer.Length, OnDataReceivedHandler, buffer);
// Start thread to manage transmission of messages
_TransmitThreadEnd = false;
_TransmitThread = new Thread(TransmitThread);
_TransmitThread.Start();
return true;
}
示例7: DoCheckState
public SensorState DoCheckState(Server target)
{
try
{
using (TcpClient client = new TcpClient())
{
var result = client.BeginConnect(target.FullyQualifiedHostName, Port, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2));
if (!success)
return SensorState.Error;
client.EndConnect(result);
}
return SensorState.OK;
}
catch (SocketException)
{
//TODO: Check for Status
return SensorState.Error;
}
catch (Exception)
{
return SensorState.Error;
}
}
示例8: Connect
public bool Connect(string ip, int port)
{
try
{
Disconnect();
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
tcpClient = new TcpClient();
tcpClient.BeginConnect(ip,
port,
new AsyncCallback(
delegate(IAsyncResult asyncResult)
{
try
{
tcpClient.EndConnect(asyncResult);
}
catch { }
autoResetEvent.Set();
}
),
tcpClient);
if (!autoResetEvent.WaitOne())
throw new Exception();
networkStream = tcpClient.GetStream();
thread = new Thread(new ThreadStart(Read));
thread.IsBackground = true;
thread.Name = "ReadThread";
thread.Start();
return true;
}
catch (Exception e)
{
ICtrl.logger.Info("Connect(...) exception:");
ICtrl.logger.Info("ip: " + ip);
ICtrl.logger.Info("port: " + port);
ICtrl.logger.Info(e.Message);
ICtrl.logger.Info(e.Source);
ICtrl.logger.Info(e.StackTrace);
DBConnection.Instance.Disconnect();
Environment.Exit(0);
}
return false;
}
示例9: Send
public bool Send(string hostName, int port = 80, bool throwOnError = true, int timeout = 100)
{
try
{
using (var tcpClient = new TcpClient())
{
var asyncResult = tcpClient.BeginConnect(hostName, port, null, null);
var asyncWaitHandle = asyncResult.AsyncWaitHandle;
try
{
if (!asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false))
{
tcpClient.Close();
if (throwOnError)
{
throw new TimeoutException();
}
return false;
}
try
{
tcpClient.EndConnect(asyncResult);
}
catch
{
if (throwOnError)
{
throw;
}
return false;
}
return true;
}
finally
{
asyncWaitHandle.Close();
}
}
}
catch
{
if (throwOnError)
{
throw;
}
return false;
}
}
示例10: IsPortOpened
/// <summary>
/// Checks, if a certain <paramref name="port"/> is opened on a given <paramref name="host"/>.
/// </summary>
/// <param name="host">IP-Address or host name to check for the port.</param>
/// <param name="port">The port-number to check.</param>
/// <param name="timeout">The timeout in seconds to wait for a reply.</param>
/// <param name="useUdp"><c>true</c> if a UDP port should be checked.</param>
/// <returns><c>True</c> if the port is opened, otherwise <c>false.</c></returns>
public static bool IsPortOpened(string host, int port, int timeout = 1, bool useUdp = false)
{
var result = false;
if (!useUdp)
{
// Use TCP
var client = new TcpClient();
try
{
client.ReceiveTimeout = timeout * 1000;
client.SendTimeout = timeout * 1000;
var asyncResult = client.BeginConnect(host, port, null, null);
var waitHandle = asyncResult.AsyncWaitHandle;
try
{
if (asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false))
{
// The result was positiv
result = client.Connected;
}
// ensure the ending-call
client.EndConnect(asyncResult);
}
finally
{
// Ensure to close the wait handle.
waitHandle.Close();
}
}
catch { }
finally
{
// wait handle didn't came back in time
client.Close();
}
}
else
{
// Use UDP
var client = new UdpClient();
try
{
client.Connect(host, port);
result = true;
}
catch { }
finally
{
// wait handle didn't came back in time
client.Close();
}
}
return result;
}
示例11: Open
public static ISocket Open(IPAddress address, int port, TimeSpan connectTimeout) {
var timeout = new ManualResetEvent(false);
Exception connectFailure = null;
var tcpClient = new TcpClient();
var ar = tcpClient.BeginConnect(address, port, r => {
try {
tcpClient.EndConnect(r);
} catch(Exception e) {
connectFailure = e;
} finally {
timeout.Set();
}
}, null);
if(!timeout.WaitOne(connectTimeout)) {
tcpClient.EndConnect(ar);
throw new TimeoutException();
}
if(connectFailure != null) {
throw new ConnectException(connectFailure);
}
return new SocketAdapter(tcpClient);
}
示例12: ConnectTo
public static Future<TcpClient> ConnectTo (string host, int port) {
var f = new Future<TcpClient>();
TcpClient client = new TcpClient();
client.BeginConnect(host, port, (ar) => {
try {
client.EndConnect(ar);
f.Complete(client);
} catch (FutureHandlerException) {
throw;
} catch (Exception ex) {
f.Fail(ex);
client.Close();
}
}, null);
return f;
}
示例13: CheckAvailable
public void CheckAvailable(int timeout)
{
TcpClient FClient = new TcpClient();
var result = FClient.BeginConnect(Server, Port, null, null);
bool success = result.AsyncWaitHandle.WaitOne(timeout, true);
if (success)
{
FClient.EndConnect(result);
FClient.Close();
Available = true;
}
else
{
FClient.Close();
Available = false;
}
}
示例14: ConnectTcpSocket
private static void ConnectTcpSocket(TcpClient client, string hostName, int port, TimeSpan timeout)
{
var ar = client.BeginConnect(hostName, port, null, null);
var wh = ar.AsyncWaitHandle;
try
{
if (!ar.AsyncWaitHandle.WaitOne(timeout, false))
{
client.Close();
throw new TimeoutException();
}
client.EndConnect(ar);
}
finally
{
wh.Close();
}
}
示例15: ConnectAPM
//public bool ConnectLocking(string host, int port)
//{
// using (var tcp = new TcpClient())
// {
// //add time out here?
// tcp.Connect(host, port);
// return tcp.Connected;
// }
//}
public bool ConnectAPM(string host, int port)
{
using (var tcp = new TcpClient())
{
var ar = tcp.BeginConnect(host, port, null, null);
using (ar.AsyncWaitHandle)
{
//Wait 2 seconds for connection.
if (ar.AsyncWaitHandle.WaitOne(500, false))
{
tcp.EndConnect(ar);
return true;
//Connect was successful.
}
}
}
return false;
}