protected BlockingConnection connect(boolean ultrapeer) throws Exception { ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); ss.bind(new InetSocketAddress(0)); connectionServices.connectToHostAsynchronously( "127.0.0.1", ss.getLocalPort(), ConnectType.PLAIN); Socket socket = ss.accept(); ss.close(); socket.setSoTimeout(3000); InputStream in = socket.getInputStream(); String word = IOUtils.readWord(in, 9); if (!word.equals("GNUTELLA")) throw new IOException("Bad word: " + word); HandshakeResponder responder; if (ultrapeer) { responder = new UltrapeerResponder(); } else { responder = new OldResponder(); } BlockingConnection con = blockingConnectionFactory.createConnection(socket); con.initialize(null, responder, 1000); replyToPing(con, ultrapeer); return con; }
private void readNumConnectBacks(int num, BlockingConnection conn, int timeout) throws Exception { Message m; for (int i = 0; i < num; i++) { do { m = conn.receive(timeout); } while (!(m instanceof TCPConnectBackVendorMessage)); } try { do { m = conn.receive(timeout); } while (!(m instanceof TCPConnectBackVendorMessage)); fail("got extra message " + m.getClass() + " on " + conn); } catch (IOException expected) { } }
/** Note that this function will _EAT_ messages until it finds a ping to respond to. */ private void replyToPing(BlockingConnection c, boolean ultrapeer) throws Exception { // respond to a ping iff one is given. Message m = null; byte[] guid; try { while (!(m instanceof PingRequest)) { m = c.receive(500); } guid = ((PingRequest) m).getGUID(); } catch (InterruptedIOException iioe) { // nothing's coming, send a fake pong anyway. guid = new GUID().bytes(); } Socket socket = c.getSocket(); PingReply reply = pingReplyFactory.createExternal( guid, (byte) 7, socket.getLocalPort(), ultrapeer ? ultrapeerIP : oldIP, ultrapeer); reply.hop(); c.send(reply); c.flush(); }