public connect ( string host, int port ) : bool | ||
host | string | |
port | int | |
return | bool |
public bool connect(string host, int port)
{
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connected_host = host;
connected_port = port;
if (!setNonBlocking())
throw new Exception("Failed to make socket nonblocking");
setNoDelay(true);
IPAddress IPA = null;
if (!IPAddress.TryParse(host, out IPA))
{
foreach (IPAddress ipa in Dns.GetHostAddresses(host).Where(ipa => !ipa.ToString().Contains(":")))
{
IPA = ipa;
break;
}
if (IPA == null)
{
close();
EDB.WriteLine("Couldn't resolve host name [{0}]", host);
return false;
}
}
if (IPA == null)
return false;
IPEndPoint ipep = new IPEndPoint(IPA, port);
LocalEndPoint = ipep;
DateTime connectionAttempted = DateTime.Now;
IAsyncResult asyncres;
lock (this)
asyncres = sock.BeginConnect(ipep, iar =>
{
lock(this)
if (sock != null)
try
{
sock.EndConnect(iar);
}
catch (Exception e)
{
EDB.WriteLine(e);
}
}, null);
bool completed = false;
while (ROS.ok && !ROS.shutting_down)
{
#pragma warning disable 665
if ((completed = asyncres.AsyncWaitHandle.WaitOne(10,false)))
#pragma warning restore 665
break;
if (DateTime.Now.Subtract(connectionAttempted).TotalSeconds >= 3)
{
EDB.WriteLine("TRYING TO CONNECT FOR " + DateTime.Now.Subtract(connectionAttempted).TotalSeconds + "s\t: " + this);
if (!asyncres.AsyncWaitHandle.WaitOne(100,true))
{
sock.Close();
sock = null;
}
}
}
if (!completed || sock == null || !sock.Connected)
return false;
return ROS.ok && initializeSocket();
}
private void onRetryTimer(object o) { #if DEBUG EDB.WriteLine("TransportPublisherLink: onRetryTimer"); #endif if (dropping) { return; } if (needs_retry && DateTime.Now.Subtract(next_retry).TotalMilliseconds < 0) { retry_period = TimeSpan.FromSeconds((retry_period.TotalSeconds > 20) ? 20 : (2 * retry_period.TotalSeconds)); needs_retry = false; TcpTransport old_transport = connection.transport; string host = old_transport.connected_host; int port = old_transport.connected_port; TcpTransport transport = new TcpTransport(); if (transport.connect(host, port)) { Connection conn = new Connection(); conn.initialize(transport, false, null); initialize(conn); ConnectionManager.Instance.addConnection(conn); } } }