Ejemplo n.º 1
0
    @Override
    public void run() {

      assert (socket == null);

      try {
        // Setup Socket
        Logger.logf(Logger.INFO, "%s starting.", name());
        this.socket = CommonIO.setupNetSocket(host, port);

        // Initialize
        BufferedOutputStream _out = new BufferedOutputStream(socket.getOutputStream());
        BufferedInputStream _in = new BufferedInputStream(socket.getInputStream());

        DataOutputStream out = new DataOutputStream(_out);
        DataInputStream in = new DataInputStream(_in);

        out.writeInt(0);
        out.flush();

        int recv = in.readInt();
        if (recv != 0) throw new SequenceErrorException(0, recv);

        out.writeInt(NBConstants.VERSION);
        out.flush();
        recv = in.readInt();
        if (recv != NBConstants.VERSION) {
          Logger.log(
              Logger.WARN,
              "WARNING: NetIO connected to robot with version "
                  + recv
                  + " but client is running version "
                  + NBConstants.VERSION
                  + " !!\n");
        }

        synchronized (this) {
          if (this.state != IOState.STARTING) return;
          this.state = IOState.RUNNING;
        }

        Events.GStreamIOStatus.generate(this, true);

        // Stream
        int seq_num = 1;
        while (state() == IOState.RUNNING) {
          recv = in.readInt();

          if (recv == 0) {
            // Pinged, no logs to receive.
            out.writeInt(0);
            out.flush();
          } else if (recv == seq_num) {
            Log nl = CommonIO.readLog(in);

            nl.tree().append(SExpr.newKeyValue("from_address", this.host));
            Logger.log(
                Logger.INFO,
                this.name()
                    + ": thread got packet of data size: "
                    + nl.bytes.length
                    + " desc: "
                    + nl.description(50));

            nl.source = SOURCE.NETWORK;

            GIOFirstResponder.generateReceived(this, ifr, 0, nl);
            ++seq_num;
          } else {
            throw new SequenceErrorException(seq_num, recv);
          }
        }

      } catch (Throwable t) {
        if (t instanceof SequenceErrorException) {
          Logger.logf(Logger.ERROR, "%s", ((SequenceErrorException) t).toString());
        }

        t.printStackTrace();
      } finally {
        Logger.logf(Logger.INFO, "%s cleaning up...", name());

        this.finish();

        StreamIO.remove(this);
        GIOFirstResponder.generateFinished(this, this.ifr);
        Events.GStreamIOStatus.generate(this, false);
      }
    }