Example #1
0
  public void run() {
    while (true) {
      try {
        System.out.println("Server name: " + serverSocket.getInetAddress().getHostName());
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Just connected to " + server.getRemoteSocketAddress());

        ObjectInputStream objectIn = new ObjectInputStream(server.getInputStream());

        try {
          Recipe rec = (Recipe) objectIn.readObject();
          startHMI(rec, rec.getProductName());

          //				System.out.println("Object Received: width: "+rec.getWidth()+" height:
          // "+rec.getHeight());
        } catch (ClassNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        DataOutputStream out = new DataOutputStream(server.getOutputStream());
        out.writeUTF(
            "Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
        server.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }
  @Test
  public void testSocketBind() throws Exception {
    final InetAddress localAddress = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
    final int localPort = 8888;
    final InetAddress remoteAddress = InetAddress.getByAddress(new byte[] {10, 0, 0, 2});
    final int remotePort = 80;
    final InetSocketAddress localSockAddress = new InetSocketAddress(localAddress, localPort);
    final InetSocketAddress remoteSockAddress = new InetSocketAddress(remoteAddress, remotePort);
    Mockito.when(socket.getLocalSocketAddress()).thenReturn(localSockAddress);
    Mockito.when(socket.getRemoteSocketAddress()).thenReturn(remoteSockAddress);
    Mockito.when(socket.getLocalAddress()).thenReturn(localAddress);
    Mockito.when(socket.getLocalPort()).thenReturn(localPort);
    Mockito.when(socket.getInetAddress()).thenReturn(remoteAddress);
    Mockito.when(socket.getPort()).thenReturn(remotePort);
    conn.bind(socket);

    Assert.assertEquals("127.0.0.1:8888<->10.0.0.2:80", conn.toString());
    Assert.assertTrue(conn.isOpen());
    Assert.assertEquals(8888, conn.getLocalPort());
    Assert.assertEquals(80, conn.getRemotePort());
    Assert.assertEquals(
        InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), conn.getLocalAddress());
    Assert.assertEquals(
        InetAddress.getByAddress(new byte[] {10, 0, 0, 2}), conn.getRemoteAddress());
  }
Example #3
0
  public void executa() {
    try {
      cliente = new Socket(this.host, Servidor.serverPort);
      System.out.println(
          "PortaLocal do socket: "
              + cliente.getLocalPort()
              + "\nPorta conectada: "
              + cliente.getPort()
              + "\nLocalSocketAddress: "
              + cliente.getLocalSocketAddress()
              + "\nInetAddress: "
              + cliente.getInetAddress()
              + "\nRemoteSocketAddress: "
              + cliente.getRemoteSocketAddress());
      System.out.println("Cliente conectado!");
      System.out.println("testes");

      // thread para receber mensagens do servidor
      ImpressoraCliente r = new ImpressoraCliente(cliente.getInputStream());
      new Thread(r).start();

      conectado = true;
      mainWindow.conectado(this);
      // cliente.close();

    } catch (IOException e) {
      mainWindow.getTextConsole().setText("Não foi possível se conectar ao servidor.");
      conectado = false;
      System.err.println(e.getMessage());
    }
  }
Example #4
0
  @Override
  public void run() {
    while (true) {
      System.out.println(
          "server started .... waiting for client" + "on port no. " + server.getLocalPort());
      // now make server eligible to connect and accept client req
      try {
        Socket socket = server.accept(); // server is now connected
        System.out.println("Just got connected to " + socket.getRemoteSocketAddress());
        // read the client message
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        System.out.println(dis.readUTF());
        // giving response to the client
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeUTF(
            "Thank your so much for connecting ..."
                + "to "
                + socket.getLocalSocketAddress()
                + "\n Goodbye Have a nice Day!!!");
        socket.close();

      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    } // end of while
  } // end of run
Example #5
0
 public void start() throws IOException {
   while (true) { // Бесконечный цикл ожидания подключений
     Socket socket = serverSocket.accept(); // Как только клиен присоединился
     ui.println("Client connected with " + socket.getLocalSocketAddress());
     new ClientThread(socket, ui); // Выделяем ему поток
   }
 }
 @Override
 public String toString() {
   Socket socket = this.socketChannel.socket();
   SocketAddress localSocketAddress = socket != null ? socket.getLocalSocketAddress() : null;
   SocketAddress remoteSocketAddress = socket != null ? socket.getRemoteSocketAddress() : null;
   return "Connection ["
       + localSocketAddress
       + " -> "
       + remoteSocketAddress
       + "], endpoint="
       + endPoint
       + ", live="
       + live
       + ", type="
       + type;
 }
  /** crates a websocket with client role */
  public WebSocketImpl(WebSocketListener listener, Draft draft, Socket sock) {
    if (listener == null || sock == null || (draft == null && role == Role.SERVER))
      throw new IllegalArgumentException("parameters must not be null");
    if (!sock.isBound()) {
      throw new IllegalArgumentException("socket has to be bound");
    }
    this.outQueue = new LinkedBlockingQueue<ByteBuffer>();
    inQueue = new LinkedBlockingQueue<ByteBuffer>();
    this.wsl = listener;
    this.role = Role.CLIENT;
    if (draft != null) this.draft = draft.copyInstance();

    localSocketAddress = (InetSocketAddress) sock.getLocalSocketAddress();
    remoteSocketAddress = (InetSocketAddress) sock.getRemoteSocketAddress();
    assert (localSocketAddress != null);
    assert (remoteSocketAddress != null);
  }
Example #8
0
  public static void main(String[] args) {
    String serverName = args[0];
    int port = Integer.parseInt(args[1]);
    try {
      System.out.println("Connecting to " + serverName + " on port " + port);
      Socket client = new Socket(serverName, port);
      System.out.println("Just connected to " + client.getRemoteSocketAddress());
      OutputStream outToServer = client.getOutputStream();
      DataOutputStream out = new DataOutputStream(outToServer);

      out.writeUTF("Hello from " + client.getLocalSocketAddress());
      InputStream inFromServer = client.getInputStream();
      DataInputStream in = new DataInputStream(inFromServer);
      System.out.println("Server says " + in.readUTF());
      client.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #9
0
    /** Releases the socket when the input stream is closed. */
    private void releaseSocket() {
      try {
        if (socket != null && !socket.isClosed()) {
          if (logger.isDebugEnabled()) {
            // some dirty workaround for IBM JSSE's SSL implementation,
            // which closes sockets asynchronously by that point.
            final SocketAddress socketAddress = socket.getLocalSocketAddress();
            if (socketAddress == null) {
              logger.debug("Listener has already been closed by other process.");
            } else {
              logger.debug("Closing listener: " + socketAddress);
            }
          }

          shutdownSocket();
          socket.close();
        }
      } catch (IOException e) {
        logger.warn("Socket close failed with: " + e);
      }
    }
Example #10
0
 public void run() {
   while (true) {
     try {
       System.out.println("Waiting for client on port" + serverSocket.getLocalPort() + "....");
       Socket server = serverSocket.accept();
       System.out.println("Just connected to " + server.getRemoteSocketAddress());
       DataInputStream in = new DataInputStream(server.getInputStream());
       System.out.println(in.readUTF());
       DataOutputStream out = new DataOutputStream(server.getOutputStream());
       out.writeUTF(
           "THank you for connecting to " + server.getLocalSocketAddress() + "See ya next time!");
       server.close();
     } catch (SocketTimeoutException s) {
       System.out.println("Timed out!");
       break;
     } catch (IOException e) {
       e.printStackTrace();
       break;
     }
   }
 }
  private void processTraceObject(
      final Trace trace, Object target, Object[] args, Throwable throwable) {
    // end spanEvent
    try {
      SpanEventRecorder recorder = trace.currentSpanEventRecorder();
      // TODO Might need a way to collect and record method arguments
      // trace.recordAttribute(...);
      recorder.recordException(throwable);
      recorder.recordApi(this.descriptor);
    } catch (Throwable t) {
      logger.warn("Error processing trace object. Cause:{}", t.getMessage(), t);
    } finally {
      trace.traceBlockEnd();
    }

    // end root span
    SpanRecorder recorder = trace.getSpanRecorder();
    String methodUri = getMethodUri(target);
    recorder.recordRpcName(methodUri);
    // retrieve connection information
    String localIpPort = UNKNOWN_ADDRESS;
    String remoteAddress = UNKNOWN_ADDRESS;
    if (args.length == 2 && args[0] instanceof TProtocol) {
      TProtocol inputProtocol = (TProtocol) args[0];
      if (this.socketAccessor.isApplicable(inputProtocol.getTransport())) {
        Socket socket = this.socketAccessor.get(inputProtocol.getTransport());
        if (socket != null) {
          localIpPort = ThriftUtils.getHostPort(socket.getLocalSocketAddress());
          remoteAddress = ThriftUtils.getHost(socket.getRemoteSocketAddress());
        }
      }
    }
    if (localIpPort != UNKNOWN_ADDRESS) {
      recorder.recordEndPoint(localIpPort);
    }
    if (remoteAddress != UNKNOWN_ADDRESS) {
      recorder.recordRemoteAddress(remoteAddress);
    }
  }
  /**
   * Send a message to a specified address.
   *
   * @param message Pre-formatted message to send.
   * @param receiverAddress Address to send it to.
   * @param receiverPort Receiver port.
   * @throws IOException If there is a problem connecting or sending.
   */
  public synchronized void sendMessage(
      byte message[], InetAddress receiverAddress, int receiverPort, boolean retry)
      throws IOException {
    if (message == null || receiverAddress == null)
      throw new IllegalArgumentException("Null argument");

    if (peerPortAdvertisedInHeaders <= 0) {
      if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
        logger.logDebug(
            "receiver port = " + receiverPort + " for this channel " + this + " key " + key);
      }
      if (receiverPort <= 0) {
        // if port is 0 we assume the default port for TCP
        this.peerPortAdvertisedInHeaders = 5060;
      } else {
        this.peerPortAdvertisedInHeaders = receiverPort;
      }
      if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
        logger.logDebug(
            "2.Storing peerPortAdvertisedInHeaders = "
                + peerPortAdvertisedInHeaders
                + " for this channel "
                + this
                + " key "
                + key);
      }
    }

    Socket sock = null;
    IOException problem = null;
    try {
      sock =
          this.sipStack.ioHandler.sendBytes(
              this.messageProcessor.getIpAddress(),
              receiverAddress,
              receiverPort,
              "TCP",
              message,
              retry,
              this);
    } catch (IOException any) {
      problem = any;
      logger.logWarning(
          "Failed to connect "
              + this.peerAddress
              + ":"
              + receiverPort
              + " but trying the advertised port="
              + this.peerPortAdvertisedInHeaders
              + " if it's different than the port we just failed on");
      logger.logError("Error is ", any);
    }
    if (sock
        == null) { // http://java.net/jira/browse/JSIP-362 If we couldn't connect to the host, try
                   // the advertised host:port as failsafe
      if (peerAddressAdvertisedInHeaders != null && peerPortAdvertisedInHeaders > 0) {
        if (logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
          logger.logWarning(
              "Couldn't connect to receiverAddress = "
                  + receiverAddress
                  + " receiverPort = "
                  + receiverPort
                  + " key = "
                  + key
                  + " retrying on peerPortAdvertisedInHeaders "
                  + peerPortAdvertisedInHeaders);
        }
        InetAddress address = InetAddress.getByName(peerAddressAdvertisedInHeaders);
        sock =
            this.sipStack.ioHandler.sendBytes(
                this.messageProcessor.getIpAddress(),
                address,
                this.peerPortAdvertisedInHeaders,
                "TCP",
                message,
                retry,
                this);
        this.peerPort = this.peerPortAdvertisedInHeaders;
        this.peerAddress = address;
        this.key = MessageChannel.getKey(peerAddress, peerPort, "TCP");
        if (logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
          logger.logWarning(
              "retry suceeded to peerAddress = "
                  + peerAddress
                  + " peerPort = "
                  + peerPort
                  + " key = "
                  + key);
        }
      } else {
        throw problem; // throw the original excpetion we had from the first attempt
      }
    }

    if (sock != mySock && sock != null) {
      if (mySock != null) {
        if (logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
          logger.logWarning("Old socket different than new socket on channel " + key);
          logger.logStackTrace();
          logger.logWarning("Old socket local ip address " + mySock.getLocalSocketAddress());
          logger.logWarning("Old socket remote ip address " + mySock.getRemoteSocketAddress());
          logger.logWarning("New socket local ip address " + sock.getLocalSocketAddress());
          logger.logWarning("New socket remote ip address " + sock.getRemoteSocketAddress());
        }
        close(false, false);
      }
      if (problem == null) {
        if (mySock != null) {
          if (logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
            logger.logWarning(
                "There was no exception for the retry mechanism so creating a new thread based on the new socket for incoming "
                    + key);
          }
        }
        mySock = sock;
        this.myClientInputStream = mySock.getInputStream();
        this.myClientOutputStream = mySock.getOutputStream();
        // start a new reader on this end of the pipe.
        Thread mythread = new Thread(this);
        mythread.setDaemon(true);
        mythread.setName("TCPMessageChannelThread");
        mythread.start();
      } else {
        if (logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
          logger.logWarning(
              "There was an exception for the retry mechanism so not creating a new thread based on the new socket for incoming "
                  + key);
        }
        mySock = sock;
      }
    }
  }
  /**
   * Send message to whoever is connected to us. Uses the topmost via address to send to.
   *
   * @param msg is the message to send.
   * @param isClient
   */
  protected synchronized void sendMessage(byte[] msg, boolean isClient) throws IOException {

    if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
      logger.logDebug("sendMessage isClient  = " + isClient);
    }

    Socket sock = null;
    IOException problem = null;
    try {
      sock =
          this.sipStack.ioHandler.sendBytes(
              this.messageProcessor.getIpAddress(),
              this.peerAddress,
              this.peerPort,
              this.peerProtocol,
              msg,
              isClient,
              this);
    } catch (IOException any) {
      problem = any;
      logger.logWarning(
          "Failed to connect "
              + this.peerAddress
              + ":"
              + this.peerPort
              + " but trying the advertised port="
              + this.peerPortAdvertisedInHeaders
              + " if it's different than the port we just failed on");
    }
    if (sock
        == null) { // http://java.net/jira/browse/JSIP-362 If we couldn't connect to the host, try
                   // the advertised host and port as failsafe
      if (peerAddressAdvertisedInHeaders != null && peerPortAdvertisedInHeaders > 0) {
        if (logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
          logger.logWarning(
              "Couldn't connect to peerAddress = "
                  + peerAddress
                  + " peerPort = "
                  + peerPort
                  + " key = "
                  + key
                  + " retrying on peerPortAdvertisedInHeaders "
                  + peerPortAdvertisedInHeaders);
        }
        InetAddress address = InetAddress.getByName(peerAddressAdvertisedInHeaders);
        sock =
            this.sipStack.ioHandler.sendBytes(
                this.messageProcessor.getIpAddress(),
                address,
                this.peerPortAdvertisedInHeaders,
                this.peerProtocol,
                msg,
                isClient,
                this);
        this.peerPort = this.peerPortAdvertisedInHeaders;
        this.peerAddress = address;
        this.key = MessageChannel.getKey(peerAddress, peerPort, "TCP");
        if (logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
          logger.logWarning(
              "retry suceeded to peerAddress = "
                  + peerAddress
                  + " peerPortAdvertisedInHeaders = "
                  + peerPortAdvertisedInHeaders
                  + " key = "
                  + key);
        }
      } else {
        throw problem; // throw the original excpetion we had from the first attempt
      }
    }

    // Created a new socket so close the old one and stick the new
    // one in its place but dont do this if it is a datagram socket.
    // (could have replied via udp but received via tcp!).
    // if (mySock == null && s != null) {
    // this.uncache();
    // } else
    if (sock != mySock && sock != null) {
      if (mySock != null) {
        if (logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
          logger.logWarning("Old socket different than new socket on channel " + key);
          logger.logStackTrace();
          logger.logWarning("Old socket local ip address " + mySock.getLocalSocketAddress());
          logger.logWarning("Old socket remote ip address " + mySock.getRemoteSocketAddress());
          logger.logWarning("New socket local ip address " + sock.getLocalSocketAddress());
          logger.logWarning("New socket remote ip address " + sock.getRemoteSocketAddress());
        }
        close(false, false);
      }
      if (problem == null) {
        if (mySock != null) {
          if (logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
            logger.logWarning(
                "There was no exception for the retry mechanism so creating a new thread based on the new socket for incoming "
                    + key);
          }
        }
        mySock = sock;
        this.myClientInputStream = mySock.getInputStream();
        this.myClientOutputStream = mySock.getOutputStream();
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.setName("TCPMessageChannelThread");
        thread.start();
      } else {
        if (logger.isLoggingEnabled(LogWriter.TRACE_WARN)) {
          logger.logWarning(
              "There was an exception for the retry mechanism so not creating a new thread based on the new socket for incoming "
                  + key);
        }
        mySock = sock;
      }
    }
  }
Example #14
0
 public Address localAddress() {
   InetSocketAddress local_addr =
       sock != null ? (InetSocketAddress) sock.getLocalSocketAddress() : null;
   return local_addr != null ? new IpAddress(local_addr) : null;
 }
Example #15
0
 Object getMetricsId() {
   Socket socket = this.socketChannel.socket();
   SocketAddress localSocketAddress = socket != null ? socket.getLocalSocketAddress() : null;
   SocketAddress remoteSocketAddress = socket != null ? socket.getRemoteSocketAddress() : null;
   return getType() + "#" + localSocketAddress + "->" + remoteSocketAddress;
 }
Example #16
0
 /**
  * Constructs a handler thread
  *
  * @param The socket connected to a single client
  */
 public Handler(Socket socket) {
   this.socket = socket;
   System.out.println(socket.getLocalSocketAddress());
   System.out.println(socket.getRemoteSocketAddress());
 }
 @Override
 protected SocketAddress localAddress0() {
   return socket.getLocalSocketAddress();
 }
 @Override
 public SocketAddress getLocalSocketAddress() {
   return sock.getLocalSocketAddress();
 }
  /**
   * This thread will receive packets from the peer and process them and also listen to new
   * connections from new peers.
   */
  @Override
  public void run() {
    try {

      ia = BinaryInputArchive.getArchive(new BufferedInputStream(sock.getInputStream()));
      bufferedOutput = new BufferedOutputStream(sock.getOutputStream());
      oa = BinaryOutputArchive.getArchive(bufferedOutput);

      QuorumPacket qp = new QuorumPacket();
      ia.readRecord(qp, "packet");
      if (qp.getType() != Leader.FOLLOWERINFO && qp.getType() != Leader.OBSERVERINFO) {
        LOG.error("First packet " + qp.toString() + " is not FOLLOWERINFO or OBSERVERINFO!");
        return;
      }
      if (qp.getData() != null) {
        ByteBuffer bbsid = ByteBuffer.wrap(qp.getData());
        this.sid = bbsid.getLong();
      } else {
        this.sid = leader.followerCounter.getAndDecrement();
      }

      LOG.info("Follower sid: " + this.sid + " : info : " + leader.self.quorumPeers.get(this.sid));

      if (qp.getType() == Leader.OBSERVERINFO) {
        learnerType = LearnerType.OBSERVER;
      }

      long peerLastZxid = qp.getZxid();
      /* the default to send to the follower */
      int packetToSend = Leader.SNAP;
      long zxidToSend = 0;
      long leaderLastZxid = 0;
      /** the packets that the follower needs to get updates from * */
      long updates = peerLastZxid;

      /* we are sending the diff check if we have proposals in memory to be able to
       * send a diff to the
       */
      ReentrantReadWriteLock lock = leader.zk.getZKDatabase().getLogLock();
      ReadLock rl = lock.readLock();
      try {
        rl.lock();
        final long maxCommittedLog = leader.zk.getZKDatabase().getmaxCommittedLog();
        final long minCommittedLog = leader.zk.getZKDatabase().getminCommittedLog();
        LOG.info(
            "Synchronizing with Follower sid: "
                + this.sid
                + " maxCommittedLog ="
                + Long.toHexString(maxCommittedLog)
                + " minCommittedLog = "
                + Long.toHexString(minCommittedLog)
                + " peerLastZxid = "
                + Long.toHexString(peerLastZxid));

        LinkedList<Proposal> proposals = leader.zk.getZKDatabase().getCommittedLog();

        if (proposals.size() != 0) {
          if ((maxCommittedLog >= peerLastZxid) && (minCommittedLog <= peerLastZxid)) {

            // as we look through proposals, this variable keeps track of previous
            // proposal Id.
            long prevProposalZxid = minCommittedLog;

            // Keep track of whether we are about to send the first packet.
            // Before sending the first packet, we have to tell the learner
            // whether to expect a trunc or a diff
            boolean firstPacket = true;

            for (Proposal propose : proposals) {
              // skip the proposals the peer already has
              if (propose.packet.getZxid() <= peerLastZxid) {
                prevProposalZxid = propose.packet.getZxid();
                continue;
              } else {
                // If we are sending the first packet, figure out whether to trunc
                // in case the follower has some proposals that the leader doesn't
                if (firstPacket) {
                  firstPacket = false;
                  // Does the peer have some proposals that the leader hasn't seen yet
                  if (prevProposalZxid < peerLastZxid) {
                    // send a trunc message before sending the diff
                    packetToSend = Leader.TRUNC;
                    LOG.info("Sending TRUNC");
                    zxidToSend = prevProposalZxid;
                    updates = zxidToSend;
                  } else {
                    // Just send the diff
                    packetToSend = Leader.DIFF;
                    LOG.info("Sending diff");
                    zxidToSend = maxCommittedLog;
                  }
                }
                queuePacket(propose.packet);
                QuorumPacket qcommit =
                    new QuorumPacket(Leader.COMMIT, propose.packet.getZxid(), null, null);
                queuePacket(qcommit);
              }
            }
          } else if (peerLastZxid > maxCommittedLog) {
            packetToSend = Leader.TRUNC;
            zxidToSend = maxCommittedLog;
            updates = zxidToSend;
          }
        } else {
          // just let the state transfer happen
        }

        leaderLastZxid = leader.startForwarding(this, updates);
        if (peerLastZxid == leaderLastZxid) {
          // We are in sync so we'll do an empty diff
          packetToSend = Leader.DIFF;
          zxidToSend = leaderLastZxid;
        }
      } finally {
        rl.unlock();
      }

      QuorumPacket newLeaderQP = new QuorumPacket(Leader.NEWLEADER, leaderLastZxid, null, null);
      oa.writeRecord(newLeaderQP, "packet");
      bufferedOutput.flush();
      // Need to set the zxidToSend to the latest zxid
      if (packetToSend == Leader.SNAP) {
        zxidToSend = leader.zk.getZKDatabase().getDataTreeLastProcessedZxid();
      }
      oa.writeRecord(new QuorumPacket(packetToSend, zxidToSend, null, null), "packet");
      bufferedOutput.flush();

      /* if we are not truncating or sending a diff just send a snapshot */
      if (packetToSend == Leader.SNAP) {
        LOG.info(
            "Sending snapshot last zxid of peer is 0x"
                + Long.toHexString(peerLastZxid)
                + " "
                + " zxid of leader is 0x"
                + Long.toHexString(leaderLastZxid)
                + "sent zxid of db as 0x"
                + Long.toHexString(zxidToSend));
        // Dump data to peer
        leader.zk.getZKDatabase().serializeSnapshot(oa);
        oa.writeString("BenWasHere", "signature");
      }
      bufferedOutput.flush();

      // Mutation packets will be queued during the serialize,
      // so we need to mark when the peer can actually start
      // using the data
      //
      queuedPackets.add(new QuorumPacket(Leader.UPTODATE, -1, null, null));

      // Start sending packets
      new Thread() {
        public void run() {
          Thread.currentThread().setName("Sender-" + sock.getRemoteSocketAddress());
          try {
            sendPackets();
          } catch (InterruptedException e) {
            LOG.warn("Unexpected interruption", e);
          }
        }
      }.start();

      /*
       * Have to wait for the first ACK, wait until
       * the leader is ready, and only then we can
       * start processing messages.
       */
      qp = new QuorumPacket();
      ia.readRecord(qp, "packet");
      if (qp.getType() != Leader.ACK) {
        LOG.error("Next packet was supposed to be an ACK");
        return;
      }
      leader.processAck(this.sid, qp.getZxid(), sock.getLocalSocketAddress());

      /*
       * Wait until leader starts up
       */
      synchronized (leader.zk) {
        while (!leader.zk.isRunning()) {
          leader.zk.wait(500);
        }
      }

      while (true) {
        qp = new QuorumPacket();
        ia.readRecord(qp, "packet");

        long traceMask = ZooTrace.SERVER_PACKET_TRACE_MASK;
        if (qp.getType() == Leader.PING) {
          traceMask = ZooTrace.SERVER_PING_TRACE_MASK;
        }
        if (LOG.isTraceEnabled()) {
          ZooTrace.logQuorumPacket(LOG, traceMask, 'i', qp);
        }
        tickOfLastAck = leader.self.tick;

        ByteBuffer bb;
        long sessionId;
        int cxid;
        int type;

        switch (qp.getType()) {
          case Leader.ACK:
            if (this.learnerType == LearnerType.OBSERVER) {
              if (LOG.isDebugEnabled()) {
                LOG.debug("Received ACK from Observer  " + this.sid);
              }
            }
            leader.processAck(this.sid, qp.getZxid(), sock.getLocalSocketAddress());
            break;
          case Leader.PING:
            // Process the touches
            ByteArrayInputStream bis = new ByteArrayInputStream(qp.getData());
            DataInputStream dis = new DataInputStream(bis);
            while (dis.available() > 0) {
              long sess = dis.readLong();
              int to = dis.readInt();
              leader.zk.touch(sess, to);
            }
            break;
          case Leader.REVALIDATE:
            bis = new ByteArrayInputStream(qp.getData());
            dis = new DataInputStream(bis);
            long id = dis.readLong();
            int to = dis.readInt();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);
            dos.writeLong(id);
            boolean valid = leader.zk.touch(id, to);
            if (valid) {
              try {
                // set the session owner
                // as the follower that
                // owns the session
                leader.zk.setOwner(id, this);
              } catch (SessionExpiredException e) {
                LOG.error(
                    "Somehow session "
                        + Long.toHexString(id)
                        + " expired right after being renewed! (impossible)",
                    e);
              }
            }
            if (LOG.isTraceEnabled()) {
              ZooTrace.logTraceMessage(
                  LOG,
                  ZooTrace.SESSION_TRACE_MASK,
                  "Session 0x" + Long.toHexString(id) + " is valid: " + valid);
            }
            dos.writeBoolean(valid);
            qp.setData(bos.toByteArray());
            queuedPackets.add(qp);
            break;
          case Leader.REQUEST:
            bb = ByteBuffer.wrap(qp.getData());
            sessionId = bb.getLong();
            cxid = bb.getInt();
            type = bb.getInt();
            bb = bb.slice();
            Request si;
            if (type == OpCode.sync) {
              si = new LearnerSyncRequest(this, sessionId, cxid, type, bb, qp.getAuthinfo());
            } else {
              si = new Request(null, sessionId, cxid, type, bb, qp.getAuthinfo());
            }
            si.setOwner(this);
            leader.zk.submitRequest(si);
            break;
          default:
        }
      }
    } catch (IOException e) {
      if (sock != null && !sock.isClosed()) {
        LOG.error("Unexpected exception causing shutdown while sock " + "still open", e);
        // close the socket to make sure the
        // other side can see it being close
        try {
          sock.close();
        } catch (IOException ie) {
          // do nothing
        }
      }
    } catch (InterruptedException e) {
      LOG.error("Unexpected exception causing shutdown", e);
    } finally {
      LOG.warn(
          "******* GOODBYE "
              + (sock != null ? sock.getRemoteSocketAddress() : "<null>")
              + " ********");
      // Send the packet of death
      try {
        queuedPackets.put(proposalOfDeath);
      } catch (InterruptedException e) {
        LOG.warn("Ignoring unexpected exception", e);
      }
      shutdown();
    }
  }