// Record the IPs in the state object for later use. static void GetHostEntryCallback(IAsyncResult ar) { ResolveState ioContext = (ResolveState)ar.AsyncState; try { ioContext.IPs = Dns.EndGetHostEntry(ar); } catch (SocketException e) { ioContext.errorMsg = e.Message; } }
public bool ConnectToCore(string host, int port, string pass, ref string error) { try { IAsyncResult async_result; ResolveState resolveContext = new ResolveState(); async_result = Dns.BeginGetHostEntry(host, new AsyncCallback(GetHostEntryCallback), resolveContext); async_result.AsyncWaitHandle.WaitOne(); if (resolveContext.IPs == null) { error = resolveContext.errorMsg; return(false); } Console.WriteLine("Resolved: '{0}' -> '{1}", host, resolveContext.IPs.AddressList[0]); Console.WriteLine("Connecting to {0}:{1}", resolveContext.IPs.AddressList[0], port); IPEndPoint remoteEP = new IPEndPoint(resolveContext.IPs.AddressList[0], port); m_s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ConnectState connectContext = new ConnectState(m_s); async_result = m_s.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), connectContext); if (!async_result.AsyncWaitHandle.WaitOne(10000, true)) { error = "Timeout during connection. Possible firewall"; return(false); } if (connectContext.errorMsg != null) { error = connectContext.errorMsg; return(false); } m_tx_mem_stream = new MemoryStream(m_tx_buffer); m_sock_writer = new BinaryWriter(m_tx_mem_stream); m_rx_mem_stream = new MemoryStream(m_rx_buffer); m_sock_reader = new BinaryReader(m_rx_mem_stream); ecProto.ecLoginPacket p = new ecProto.ecLoginPacket("amule.net", "0.0.1", pass); async_result = SendPacket(p); if (!async_result.AsyncWaitHandle.WaitOne()) { // Was unable to send login request for 1sec. Line must be really slow return(false); } m_handler = new amuleLogicHandler(this); StartReceive(); Console.WriteLine("Waiting for auth done"); // FIXME: must be able to cancel this read. m_packet_op_Done.WaitOne(); if (m_rx_byte_count == -1) { // remote side terminated connection Console.WriteLine("Connection terminated on remote side"); } Console.WriteLine("Connect done"); bool result = ((amuleLogicHandler)m_handler).AuthResult(); m_handler = null; return(result); } catch (Exception e) { error = e.Message; return(false); } }