コード例 #1
0
ファイル: Server.java プロジェクト: oy-attia/RDTProtocol
  public void run() {
    printWelcome();
    while (!welcomingSocket.isClosed()) {
      while (!canCreateNewWorker()) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          continue;
        }
      }

      try {
        DatagramPacket pkt = new DatagramPacket(new byte[EXPECTED_REQ_SIZE], EXPECTED_REQ_SIZE);
        welcomingSocket.receive(pkt); // Blocks!
        RequestPacket reqPkt = new RequestPacket(pkt);

        if (reqPkt.isCorrupted()) {
          continue;
        }

        ConnectionHandler conn = new ConnectionHandler(strategy, reqPkt, plp, pep, rngSeed, maxN);
        Thread connectionHandler = new Thread(conn);
        connectionHandler.start();
        workers.add(new Worker(connectionHandler, conn, System.currentTimeMillis()));
      } catch (IOException e) {
        continue;
      }
    }
  }
コード例 #2
0
ファイル: QueueManagerProxy.java プロジェクト: jfsc/ptp
  @Override
  public String receive(Boolean transactional)
      throws IOException, InterruptedException, ClassNotFoundException {
    ClientRequestHandler crh = new ClientRequestHandler("localhost", 1313, true);
    Marshaller marshaller = new Marshaller();
    RequestPacket requestPacket = new RequestPacket();
    ReplyPacket marshalledReplyPacket = new ReplyPacket();
    byte[] unmarshalledReplyPacket = new byte[1024];
    Message message = new Message();

    // configure message
    message.setHeader(new MessageHeader(this.queueName, transactional));
    message.setBody(new MessageBody("messageBody"));

    // configure packet
    RequestPacketBody packetBody = new RequestPacketBody();
    ArrayList<Object> parameters = new ArrayList<Object>(0);
    packetBody.setParameters(parameters);
    packetBody.setMessage(message);
    requestPacket.setPacketHeader(new RequestPacketHeader("receive"));
    requestPacket.setPacketBody(packetBody);

    // send request
    crh.send(marshaller.marshall((Object) requestPacket));

    // receive reply
    unmarshalledReplyPacket = crh.receive();
    marshalledReplyPacket = (ReplyPacket) marshaller.unmarshall(unmarshalledReplyPacket);

    return marshalledReplyPacket.getReply(); // TODO
  }
コード例 #3
0
ファイル: QueueManagerProxy.java プロジェクト: jfsc/ptp
  @Override
  public void send(String m, Boolean transactional) throws IOException, InterruptedException {
    // configure
    ClientRequestHandler crh = new ClientRequestHandler("localhost", 1313, false);
    Marshaller marshaller = new Marshaller();
    RequestPacket packet = new RequestPacket();
    Message message = new Message();

    // configure message
    message.setHeader(new MessageHeader(this.queueName, transactional));
    message.setBody(new MessageBody(m));

    // configure packet
    RequestPacketBody packetBody = new RequestPacketBody();
    ArrayList<Object> parameters = new ArrayList<Object>(0);

    packetBody.setParameters(parameters);
    packetBody.setMessage(message);
    packet.setPacketHeader(new RequestPacketHeader("send"));
    packet.setPacketBody(packetBody);

    // send request
    crh.send(marshaller.marshall((Object) packet));

    return;
  }
コード例 #4
0
ファイル: TCPReceiver.java プロジェクト: Ranade/pinpoint
    @Override
    public void run() {

      byte[] bytes = requestPacket.getPayload();
      SocketAddress remoteAddress = pinpointSocket.getRemoteAddress();
      try {
        TBase<?, ?> tBase = SerializationUtils.deserialize(bytes, deserializerFactory);
        if (tBase instanceof L4Packet) {
          if (logger.isDebugEnabled()) {
            L4Packet packet = (L4Packet) tBase;
            logger.debug("tcp l4 packet {}", packet.getHeader());
          }
          return;
        }
        TBase result = dispatchHandler.dispatchRequestMessage(tBase);
        if (result != null) {
          byte[] resultBytes = SerializationUtils.serialize(result, serializerFactory);
          pinpointSocket.response(requestPacket, resultBytes);
        }
      } catch (TException e) {
        if (logger.isWarnEnabled()) {
          logger.warn(
              "packet serialize error. SendSocketAddress:{} Cause:{}",
              remoteAddress,
              e.getMessage(),
              e);
        }
        if (logger.isDebugEnabled()) {
          logger.debug("packet dump hex:{}", PacketUtils.dumpByteArray(bytes));
        }
      } catch (Exception e) {
        // there are cases where invalid headers are received
        if (logger.isWarnEnabled()) {
          logger.warn(
              "Unexpected error. SendSocketAddress:{} Cause:{}", remoteAddress, e.getMessage(), e);
        }
        if (logger.isDebugEnabled()) {
          logger.debug("packet dump hex:{}", PacketUtils.dumpByteArray(bytes));
        }
      }
    }
コード例 #5
0
ファイル: ThreadWorker.java プロジェクト: saknis/Avuna-HTTPD
  public void run() {
    while (keepRunning) {
      RequestPacket incomingRequest = host.pollReqQueue();
      if (incomingRequest == null) {
        try {
          synchronized (this) {
            this.wait();
          }
        } catch (InterruptedException e) {
        }
        continue;
      }
      try {
        if (incomingRequest.host == null) {
          incomingRequest.work.close(); // TODO 500 ISE
          continue;
        }
        if (incomingRequest.host.isForwarding()) {
          VHost vh = incomingRequest.host;
          if (incomingRequest.work.fn == null) {
            incomingRequest.work.fn =
                vh.isForwardUnix()
                    ? new UnixSocket(vh.getForwardIP())
                    : new Socket(vh.getForwardIP(), vh.getForwardPort());
            incomingRequest.work.fnout =
                new DataOutputStream(incomingRequest.work.fn.getOutputStream());
            incomingRequest.work.fnout.flush();
            incomingRequest.work.fnin =
                new DataInputStream(incomingRequest.work.fn.getInputStream());
          }
          incomingRequest.headers.addHeader(
              "X-Forwarded-For", incomingRequest.work.s.getInetAddress().getHostAddress());
          incomingRequest.write(incomingRequest.work.fnout);
          incomingRequest.work.fnout.flush();
          ResponsePacket outgoingResponse = incomingRequest.child;
          outgoingResponse.request = incomingRequest;
          String line = Stream.readLine(incomingRequest.work.fnin);
          if (line == null) {
            incomingRequest.work.close();
            continue;
          }
          if (line.length() == 0) {
            line = Stream.readLine(incomingRequest.work.fnin);
          }
          int i = line.indexOf(" ");
          outgoingResponse.httpVersion = line.substring(0, i);
          i++;
          outgoingResponse.statusCode =
              Integer.parseInt(line.substring(i, (i = line.indexOf(" ", i))));
          i++;
          outgoingResponse.reasonPhrase = line.substring(i);
          while ((line = Stream.readLine(incomingRequest.work.fnin)).length() > 0) {
            outgoingResponse.headers.addHeader(line);
          }

          if (outgoingResponse.headers.hasHeader("Content-Length")) {
            byte[] data =
                new byte[Integer.parseInt(outgoingResponse.headers.getHeader("Content-Length"))];
            incomingRequest.work.fnin.readFully(data);
            // readLine(incomingRequest.work.cn.in);
            outgoingResponse.body =
                new Resource(
                    data,
                    outgoingResponse.headers.hasHeader("Content-Type")
                        ? outgoingResponse.headers.getHeader("Content-Type")
                        : "text/html; charset=utf-8");
            outgoingResponse.prewrite();
            outgoingResponse.done = true;
            outgoingResponse.bwt = System.nanoTime();
          } else if (outgoingResponse.headers.hasHeader("Transfer-Encoding")
              && outgoingResponse.headers.getHeader("Transfer-Encoding").contains("chunked")) {
            outgoingResponse.toStream = incomingRequest.work.fnin;
            outgoingResponse.done = true;
            outgoingResponse.bwt = System.nanoTime();
          } else {
            outgoingResponse.bwt = System.nanoTime();
            // no body
          }
        } else {
          Benchmark bm = new Benchmark(false);
          bm.startSection("req");
          bm.startSection("head");
          ResponsePacket outgoingResponse = incomingRequest.child;
          outgoingResponse.request = incomingRequest;
          boolean main = outgoingResponse.request.parent == null;
          String add = main ? "" : "-SUB";
          long benchStart = System.nanoTime();
          bm.endSection("head");
          bm.startSection("preproc");
          EventPreprocessRequest epr = new EventPreprocessRequest(incomingRequest);
          incomingRequest.host.eventBus.callEvent(epr);
          if (incomingRequest.drop || epr.isCanceled()) {
            incomingRequest.work.close();
            incomingRequest.host.logger.log(
                incomingRequest.userIP
                    + " "
                    + incomingRequest.method.name
                    + add
                    + " "
                    + incomingRequest.host.getHostPath()
                    + incomingRequest.target
                    + " DROPPED took: "
                    + (System.nanoTime() - benchStart) / 1000000D
                    + " ms");
            continue;
          }
          bm.endSection("preproc");
          bm.startSection("rg");
          ResponseGenerator.process(incomingRequest, outgoingResponse);
          bm.endSection("rg");
          bm.startSection("gen-resp");
          EventGenerateResponse epr2 = new EventGenerateResponse(incomingRequest, outgoingResponse);
          incomingRequest.host.eventBus.callEvent(epr2);
          if (epr2.isCanceled() || outgoingResponse.drop) {
            incomingRequest.work.close();
            incomingRequest.host.logger.log(
                incomingRequest.userIP
                    + " "
                    + incomingRequest.method.name
                    + add
                    + " "
                    + incomingRequest.host.getHostPath()
                    + incomingRequest.target
                    + " DROPPED took: "
                    + (System.nanoTime() - benchStart) / 1000000D
                    + " ms");
            continue;
          }
          bm.endSection("gen-resp");
          bm.startSection("resp-finished");
          EventResponseFinished epr3 = new EventResponseFinished(outgoingResponse);
          incomingRequest.host.eventBus.callEvent(epr3);
          if (epr3.isCanceled() || outgoingResponse.drop) {
            incomingRequest.work.close();
            incomingRequest.host.logger.log(
                incomingRequest.userIP
                    + " "
                    + incomingRequest.method.name
                    + add
                    + " "
                    + incomingRequest.host.getHostPath()
                    + incomingRequest.target
                    + " DROPPED took: "
                    + (System.nanoTime() - benchStart) / 1000000D
                    + " ms");
            continue;
          }
          bm.endSection("resp-finished");
          bm.startSection("prewrite");
          if (main) outgoingResponse.prewrite();
          else outgoingResponse.subwrite();
          if (outgoingResponse.drop) {
            incomingRequest.work.close();
            incomingRequest.host.logger.log(
                incomingRequest.userIP
                    + " "
                    + incomingRequest.method.name
                    + add
                    + " "
                    + incomingRequest.host.getHostPath()
                    + incomingRequest.target
                    + " DROPPED took: "
                    + (outgoingResponse.bwt - benchStart) / 1000000D
                    + " ms");
            continue;
          }
          bm.endSection("prewrite");
          bm.startSection("post");
          outgoingResponse.done = true;
          if (host.unio() && main) {
            ResponsePacket peek;
            Work focus = incomingRequest.work;
            while ((peek = focus.outQueue.peek()) != null && peek.done) {
              focus.outQueue.poll();
              boolean t = peek.reqTransfer;
              if (peek.reqStream != null) {
                ThreadJavaLoaderStreamWorker sw =
                    new ThreadJavaLoaderStreamWorker(
                        host, focus, peek.request, peek, peek.reqStream);
                host.subworkers.add(sw);
                sw.start();
              } else if (peek.toStream != null) {
                ThreadRawStreamWorker sw =
                    new ThreadRawStreamWorker(host, focus, peek, peek.toStream);
                host.subworkers.add(sw);
                sw.start();
              } else if (t && peek.body != null) {
                ThreadStreamWorker sw = new ThreadStreamWorker(host, focus, peek.request, peek);
                host.subworkers.add(sw);
                sw.start();
              } else {
                focus.out.write(peek.subwrite);
                // TODO: remove from input?
              }
            }
          }
          incomingRequest.host.eventBus.callEvent(new EventResponseSent(outgoingResponse));
          // Logger.log((benchStart - ps) / 1000000D + " ps-start");
          // Logger.log((set - benchStart) / 1000000D + " start-set");
          // Logger.log((proc1 - set) / 1000000D + " set-proc1");
          // Logger.log((resp - proc1) / 1000000D + " proc1-resp");
          // Logger.log((proc2 - resp) / 1000000D + " resp-proc2");
          // Logger.log((write - proc2) / 1000000D + " proc2-write");
          // Logger.log((cur - write) / 1000000D + " write-cur");
          if (incomingRequest.host.getDebug()) {
            incomingRequest.host.logger.log(AvunaHTTPD.crlf + incomingRequest.toString().trim());
          }
          incomingRequest.host.logger.log(
              incomingRequest.userIP
                  + " "
                  + incomingRequest.method.name
                  + add
                  + " "
                  + incomingRequest.host.getHostPath()
                  + incomingRequest.target
                  + " returned "
                  + outgoingResponse.statusCode
                  + " "
                  + outgoingResponse.reasonPhrase
                  + " took: "
                  + (outgoingResponse.bwt - benchStart) / 1000000D
                  + " ms");
          bm.endSection("post");
          bm.endSection("req");
          bm.log();
        }
      } catch (Exception e) {
        if (!(e instanceof SocketException)) {
          incomingRequest.host.logger.logError(e);
        } else {
          try {
            incomingRequest.work.s.close();
          } catch (IOException ex) {
            incomingRequest.host.logger.logError(ex);
          }
        }
      } finally {
        if (host.sizeReqQueue() < 10000) {
          try {
            Thread.sleep(0L, 100000);
          } catch (InterruptedException e) {
            // Logger.logError(e);
          }
        }
      }
    }
  }
コード例 #6
0
ファイル: PacketHandler.java プロジェクト: TheBassist95/Juxs
  private void handlePacket(Packet250CustomPayload packet, Player player) throws IOException {
    DataInputStream in = new DataInputStream(new ByteArrayInputStream(packet.data));
    EntityPlayer play = (EntityPlayer) player;

    if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) {
      if (packet.channel.equals(Reference.CHANNEL + "REMOVE")) RadioUpdatePacket.execute(packet);
      else if (packet.channel.equals(Reference.CHANNEL + "TIMEUNTIL")) {
        int ticks = in.readInt();
        int minute = ticks / 20 / 60;
        int sec = (ticks / 20) - (minute * 60);
        play.addChatMessage(String.format("Next Song will begin in %d:%02d", minute, sec));
      } else if (packet.channel.equals(Reference.CHANNEL + "REQUEST")) {
        System.out.println("REQUEST RECIEVED CLIENT");
        RequestPacket.execute(in, packet);
      } else if (packet.channel.equals(Reference.CHANNEL + "MESS")) {
        String s = in.readUTF();
        if (s.equals("FALSE")) {
          Location a = new Location(in.readInt(), in.readInt(), in.readInt());
          ((TileEntityJux)
                      ModLoader.getMinecraftInstance().theWorld.getBlockTileEntity(a.x, a.y, a.z))
                  .isDisabled =
              false;
          ((TileEntityJux)
                      ModLoader.getMinecraftInstance().theWorld.getBlockTileEntity(a.x, a.y, a.z))
                  .done =
              false;
        } else {
          ((TileEntityJux)
                      ModLoader.getMinecraftInstance()
                          .theWorld
                          .getBlockTileEntity(in.readInt(), in.readInt(), in.readInt()))
                  .isDisabled =
              true;
          play.addChatMessage(s);
        }
      } else SongPacket.execute(in, packet);

    } else {
      EntityPlayerMP p = (EntityPlayerMP) play;
      if (packet.channel.equals(Reference.CHANNEL + "TIMEUNTIL")) {
        // System.out.println("received RadioUpdate packet from player");
        new RadioUpdatePacket(
            Reference.CHANNEL + "TIMEUNTIL",
            in.readUTF(),
            (int) p.posX,
            (int) p.posY,
            (int) p.posZ);
      } else if (packet.channel.contains(Reference.CHANNEL + "CHANGE")) {
        RadioUpdatePacket.execute(packet);
      } else if (packet.channel.equals(Reference.CHANNEL + "NEXT")) {
        System.out.println("received next");
        if (MinecraftServer.getServer().isSinglePlayer()) RadioInit.getStation(in.readUTF()).next();
        else if (MinecraftServer.getServer()
            .getConfigurationManager()
            .getOps()
            .contains(play.username.toLowerCase())) RadioInit.getStation(in.readUTF()).next();
      } else if (packet.channel.equals(Reference.CHANNEL + "REQUEST")) {
        new RequestPacket(Reference.CHANNEL + "REQUEST", in.readInt(), in.readInt(), in.readInt());
      } else PacketDispatcher.sendPacketToAllPlayers(packet);
    }
  }