void checkDstOnline(link l) { string dst_ip = null; if (!sl.linked) { throw new Exception("您已离线."); } sl.query4IP(l.dst_username, out dst_ip); IPAddress addr = IPAddress.Parse(dst_ip); IPEndPoint endpoint = new IPEndPoint(addr, common.p2p_port); if (!l.linked) { bool done = false; l.sendSocket.BeginConnect(endpoint.Address, endpoint.Port, new AsyncCallback((IAsyncResult ar) => { done = true; Socket s = (Socket)ar.AsyncState; s.EndConnect(ar); }), l.sendSocket); while (!done) { ; } Console.WriteLine("successfully connect " + l.sendSocket.RemoteEndPoint); } if (!l.linked) { throw new Exception("无法连接" + l.dst_username + "的IP地址。"); } }
public void start() { if (working) { throw new Exception("您已经登录了。"); } string ip; sl.query4IP(sl.getUserName(), out ip); IPAddress ipAddress = IPAddress.Parse(ip); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, common.p2p_port); try { listenSocket.Bind(localEndPoint); listenSocket.Listen(backlog); working = true; using (BackgroundWorker bw = new BackgroundWorker()) { bw.DoWork += (object o, DoWorkEventArgs ea) => { allDone.Reset(); listenSocket.BeginAccept( new AsyncCallback(this.acceptCallback), listenSocket); Console.WriteLine("Waiting for a connection..."); allDone.WaitOne(); }; bw.RunWorkerCompleted += (object o, RunWorkerCompletedEventArgs ea) => { if (ea.Error == null && working) { bw.RunWorkerAsync(); } }; bw.RunWorkerAsync(); } } catch (System.Exception ex) { working = false; if (listenSocket.Connected) { listenSocket.Close(); } throw ex; } }