コード例 #1
1
ファイル: UDPClient.java プロジェクト: itu-cstp/MDS04
  public static void main(String[] args) throws IOException, InterruptedException {
    boolean running = true;
    // udp protocol over a socket.
    DatagramSocket socket = new DatagramSocket();

    while (running) {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String line = br.readLine();
      String[] inputs = line.split(" ");

      if (inputs.length < 2) {
        System.out.println("Usage: username command id");
        socket.close();
        return;
      }

      byte[] byteArr = (inputs[0] + " " + inputs[1] + " " + inputs[2]).getBytes();

      // send request
      byte[] buf = new byte[256];
      InetAddress address = InetAddress.getByName("localhost");
      DatagramPacket packet = new DatagramPacket(byteArr, byteArr.length, address, 4445);
      socket.send(packet);

      // get response
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      // display response
      String received = new String(packet.getData(), 0, packet.getLength());
      System.out.println("From server: " + received);
    }
    //   socket.close();
  }
コード例 #2
0
  private void listen() throws Exception {
    System.out.println("Listening on port: " + serverPort);
    // Initialize socket
    socket = new DatagramSocket(serverPort);

    // While running
    while (run) {

      // Wait for handshake
      packet = new DatagramPacket(response, response.length);
      socket.receive(packet); // Blocking
      // System.out.println("RT: got packet");
      Packet p = new Packet(packet.getData());

      if (p.isHandshake()) {
        // System.out.println("RT: is handshake");
        // Get client connection info
        InetAddress IPAddress = packet.getAddress();
        int port = packet.getPort();

        // Process handshake
        processHandshake(p, IPAddress, port);

        // Get message
        MyMessage message = getMessage();

        if (message != null) {
          rc.rreceive(message);
        }
      }
    }
  }
コード例 #3
0
ファイル: UDPClient.java プロジェクト: magnlun/cnt
  public static void main(final String... args) throws Throwable {
    final String remotehost = args[0];
    final int remoteport = Integer.parseInt(args[1]);
    final DatagramSocket socket = new DatagramSocket();

    final byte buffer[] = new byte[512];

    final InetSocketAddress remote = new InetSocketAddress(remotehost, remoteport);

    buffer[0] = ENQUIRY;
    buffer[1] = END_OF_TRANSMISSION;
    socket.send(new DatagramPacket(buffer, 2, remote));

    final DatagramPacket p = new DatagramPacket(buffer, buffer.length);
    socket.receive(p);

    if ((p.getLength() == 2) && (buffer[0] == ACKNOWLEDGE) && (buffer[1] == END_OF_TRANSMISSION))
      System.out.println("Connection established");
    else {
      System.out.println("Connection failed");
      return;
    }

    for (; ; ) {
      int ptr = 0;
      for (int d; (d = System.in.read()) != '\n'; ) buffer[ptr++] = (byte) d;

      socket.send(new DatagramPacket(buffer, ptr, remote));
    }
  }
コード例 #4
0
  public static void main(String args[]) {
    DatagramSocket skt = null;
    try {
      skt = new DatagramSocket(6789);
      byte[] buffer = new byte[1000];
      while (true) {
        DatagramPacket request = new DatagramPacket(buffer, buffer.length);
        skt.receive(request);
        System.out.println("Data received from client");
        System.out.println(new String(request.getData()));
        Thread.sleep(15000);

        String[] arrayMsg = (new String(request.getData())).split(" ");

        System.out.println(arrayMsg[0] + "server processed");

        byte[] sendMsg = (arrayMsg[0] + "server processed").getBytes();

        DatagramPacket reply =
            new DatagramPacket(sendMsg, sendMsg.length, request.getAddress(), request.getPort());

        System.out.println("sending data from server to client");
        Thread.sleep(15000);
        ;
        skt.send(reply);
      }
    } catch (Exception e) {

    }
  }
コード例 #5
0
  /**
   * Initializes a new <tt>DatagramPacket</tt> instance which is a clone of a specific
   * <tt>DatagramPacket</tt> i.e. the properties of the clone <tt>DatagramPacket</tt> are clones of
   * the specified <tt>DatagramPacket</tt>.
   *
   * @param p the <tt>DatagramPacket</tt> to clone
   * @return a new <tt>DatagramPacket</tt> instance which is a clone of the specified
   *     <tt>DatagramPacket</tt>
   */
  public static DatagramPacket clone(DatagramPacket p) {
    synchronized (p) {
      byte[] pData = p.getData();
      byte[] cData = (pData == null) ? null : pData.clone();

      return new DatagramPacket(cData, p.getOffset(), p.getLength(), p.getAddress(), p.getPort());
    }
  }
コード例 #6
0
 public static DatagramPacket makePacket(char c1[], InetAddress inetAddress) {
   // byte[] sendMsg=(c1).toString().getBytes();
   String s1 = new String(c1);
   System.out.println(c1);
   byte[] sendMsg = s1.getBytes();
   DatagramPacket packet =
       new DatagramPacket(sendMsg, sendMsg.length, inetAddress, client.PORT_NUMBER_CLIENT);
   System.out.println(new String(packet.getData()));
   return packet;
 }
コード例 #7
0
  /**
   * Creates a new <tt>RawPacket</tt> from a specific <tt>DatagramPacket</tt> in order to have this
   * instance receive its packet data through its {@link #read(byte[], int, int)} method. Returns an
   * array of <tt>RawPacket</tt> with the created packet as its first element (and <tt>null</tt> for
   * the other elements).
   *
   * <p>Allows extenders to intercept the packet data and possibly filter and/or modify it.
   *
   * @param datagramPacket the <tt>DatagramPacket</tt> containing the packet data
   * @return an array of <tt>RawPacket</tt> containing the <tt>RawPacket</tt> which contains the
   *     packet data of the specified <tt>DatagramPacket</tt> as its first element.
   */
  protected RawPacket[] createRawPacket(DatagramPacket datagramPacket) {
    RawPacket[] pkts = rawPacketArrayPool.poll();
    if (pkts == null) pkts = new RawPacket[1];

    RawPacket pkt = rawPacketPool.poll();
    if (pkt == null) pkt = new RawPacket();

    pkt.setBuffer(datagramPacket.getData());
    pkt.setFlags(0);
    pkt.setLength(datagramPacket.getLength());
    pkt.setOffset(datagramPacket.getOffset());

    pkts[0] = pkt;
    return pkts;
  }
コード例 #8
0
  private MyMessage getMessage() throws Exception {
    int dataRecieved = 0;
    String m = new String();
    String t;

    // FIXME needs to get multiple packets and messages
    // System.out.println("RT: Now waiting for message data");

    while (dataRecieved < totalDataSize) {
      // Get message data
      response = new byte[65000];
      DatagramPacket packet = new DatagramPacket(response, response.length);
      socket.receive(packet);
      Packet p = new Packet(packet.getData());
      // System.out.println("RT: Got message with seqnum: "+p.getSeqNum());

      // If we have a handshake packet something broke
      if (p.isHandshake()) {
        return null;
      }

      // If next in-order packet grab data and is not corrupt
      // XXX
      if (p.getSeqNum() == seqNum + 1 && p.checkChecksum()) {
        // Get the message ( part? )
        // System.out.println("RT: Is correct seqnum");
        t = p.getMessages().get(0).getMessageContents();
        // System.out.println("RT: Got message packet: " + t);
        m += t;

        // Send ack
        sendAck(p, packet);

        // Increment counters
        dataRecieved += t.length();
        seqNum++;
      } else {
        System.out.println("RT: Is NOT correct seqnum");
      }
    }
    MyMessage result = new MyMessage();
    result.setMessageContents(m);
    return result;
  }
コード例 #9
0
ファイル: Sender.java プロジェクト: yuanruiliu/CS2105
    public void run() {
      try {
        byte[] in_data = new byte[pkt_size];
        DatagramPacket in_pkt = new DatagramPacket(in_data, in_data.length);
        try {
          while (true) {
            sk_in.receive(in_pkt);
            System.out.print(
                (new Date().getTime())
                    + ": sender received "
                    + in_pkt.getLength()
                    + "bytes from "
                    + in_pkt.getAddress().toString()
                    + ":"
                    + in_pkt.getPort()
                    + ". data are ");
            for (int i = 0; i < pkt_size; ++i) System.out.print(in_data[i]);
            System.out.println();
            try {
              String res = new String(in_data);
              String[] arr = new String[2];
              arr = res.split(" ");
              System.out.println(arr[0]);
              System.out.println(arr[1]);
              if ((arr[0].trim().equalsIgnoreCase(String.valueOf(curr)))
                  && (arr[1].trim().equalsIgnoreCase("ACK")
                      && (arr[2].trim().equalsIgnoreCase(String.valueOf(617709412))))) {
                curr++;
              }
            } catch (Exception e) {

            }
          }

        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          sk_in.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
      }
    }
コード例 #10
0
ファイル: MulticastClient.java プロジェクト: aki-s/emacs.pub
  public static void main(String[] args) throws IOException {

    MulticastSocket socket = new MulticastSocket(4446);
    InetAddress address = InetAddress.getByName("230.0.0.1");
    socket.joinGroup(address);

    DatagramPacket packet;

    // get a few quotes
    for (int i = 0; i < 5; i++) {

      byte[] buf = new byte[256];
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      String received = new String(packet.getData(), 0, packet.getLength());
      System.out.println("Quote of the Moment: " + received);
    }

    socket.leaveGroup(address);
    socket.close();
  }
コード例 #11
0
  public void run(SoleThread st) {
    try {
      byte[] buf = new byte[MAX_HEADER_LENGTH + MAX_PACKET_LENGTH];
      int len;
      byte[] tar = null;

      while (st.isSole()) {
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        // System.out.println("recv...");
        recvSocket.receive(packet);

        len = packet.getLength();
        tar = new byte[len];
        System.arraycopy(buf, 0, tar, 0, len);

        // processMsg (tar);
        quickQueue.put(tar);
      }
    } catch (Exception e) {
      // throw new UDPBaseException ("UDPBase run() error=\n"+e.toString());
      System.out.println("Something error in recv thread!");
      e.printStackTrace();
    }
  }
コード例 #12
0
  private boolean sendAck(Packet p, DatagramPacket dp) {

    // Respond
    // System.out.println("RT: Sending ack for packet w/ seqnum: " + p.getSeqNum());
    Packet hsp = new Packet(p.getSeqNum());
    hsp.assembleHandshakePacket();
    packet =
        new DatagramPacket(hsp.getPacketData(), hsp.getPacketSize(), dp.getAddress(), dp.getPort());

    try {
      socket.send(packet);
    } catch (Exception e) {
      System.out.println("RT: Could not send ack packet:\n" + e.getMessage());
      return false;
    }

    return true;
  }
コード例 #13
0
    @Override
    public void run() {

      try {
        // Create a packet for sending data
        DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length);

        OutputStream outputStream = null;
        String fileName = "";
        boolean createFile = true;
        int bytesReceived = 0;
        long totalBytesReceived = 0;
        long fileSize = 0;

        socket.receive(receivePacket);

        // Display the client number
        textArea.append("Starting thread for UDP client " + clientNo + " at " + new Date() + '\n');

        textArea.append(
            "The client host name is "
                + receivePacket.getAddress().getHostName()
                + " and port number is "
                + receivePacket.getPort()
                + '\n');

        // Continuously serve the client
        while (true) {
          bytesReceived = receivePacket.getLength();

          if (bytesReceived
              > 0) { // Get the file transmission header from the initial client packet
            String transmitHeader = new String(receivePacket.getData(), 0, bytesReceived);
            // transmitHeader = transmitHeader.substring(0, bytesReceived).trim().;
            String[] header = transmitHeader.split(HEADER_DEL);
            fileSize = Long.parseLong(header[0]);
            fileName = header[1];

            // Send receipt acknowledgment back to the client. Just send back the number of bytes
            // received.
            setSendPacketAddress(sendPacket, receivePacket);
            sendPacket.setData(String.valueOf(bytesReceived).getBytes());
            socket.send(sendPacket);
          }

          while (totalBytesReceived < fileSize) {
            // Wait for client to send bytes
            // socket.setSendBufferSize(BUFFER_SIZE);
            socket.receive(receivePacket);
            bytesReceived = receivePacket.getLength();

            if (totalBytesReceived == 0) {
              if (createFile) { // Get a unique name for the file to be received
                // fileName = getUniqueFileName();
                fileName = textFolder.getText() + fileName;
                outputStream = createFile(fileName);
                createFile = false;
                textArea.append("Receiving file from client.\n");
              }

              // Write bytes to file
              outputStream.write(receivePacket.getData(), 0, bytesReceived);
            } else {
              if (outputStream != null) { // Write bytes to file, if any
                outputStream.write(receivePacket.getData(), 0, bytesReceived);
              }
            }

            // Increment total bytes received
            totalBytesReceived += bytesReceived;

            // Tell the client to send more data. Just send back the number of bytes received.
            sendPacket.setData(String.valueOf(bytesReceived).getBytes());
            socket.send(sendPacket);

            // buffer = new byte[BUFFER_SIZE];
            Arrays.fill(buffer, (byte) 0);

            receivePacket = new DatagramPacket(buffer, buffer.length);
          }

          outputStream.flush();
          outputStream.close();

          textArea.append("Received file successfully. Saved as " + fileName + "\n");

          // Tell the client transmission is complete. Just send back the total number of bytes
          // received.
          sendPacket.setData(String.valueOf(totalBytesReceived).getBytes());
          socket.send(sendPacket);

          // Reset creation flag
          createFile = true;
          totalBytesReceived = 0;

          // Wait for client to send another file
          socket.receive(receivePacket);
        }
      } catch (IOException e) {
        System.err.println(e);
      }
    }
コード例 #14
0
  /**
   * Listens for incoming datagrams, stores them for reading by the <tt>read</tt> method and
   * notifies the local <tt>transferHandler</tt> that there's data to be read.
   */
  public void run() {
    DatagramPacket p = new DatagramPacket(buffer, 0, PACKET_RECEIVE_BUFFER_LENGTH);

    while (!closed) {
      try {
        // http://code.google.com/p/android/issues/detail?id=24765
        if (OSUtils.IS_ANDROID) p.setLength(PACKET_RECEIVE_BUFFER_LENGTH);

        receivePacket(p);
      } catch (IOException e) {
        ioError = true;
        break;
      }

      /*
       * Do the DatagramPacketFilters accept the received DatagramPacket?
       */
      DatagramPacketFilter[] datagramPacketFilters = getDatagramPacketFilters();
      boolean accept;

      if (!enabled) accept = false;
      else if (datagramPacketFilters == null) accept = true;
      else {
        accept = true;
        for (int i = 0; i < datagramPacketFilters.length; i++) {
          try {
            if (!datagramPacketFilters[i].accept(p)) {
              accept = false;
              break;
            }
          } catch (Throwable t) {
            if (t instanceof ThreadDeath) throw (ThreadDeath) t;
          }
        }
      }

      if (accept) {
        RawPacket pkts[] = createRawPacket(p);

        for (int i = 0; i < pkts.length; i++) {
          RawPacket pkt = pkts[i];

          pkts[i] = null;

          if (pkt != null) {
            if (pkt.isInvalid()) {
              /*
               * Return pkt to the pool because it is invalid and,
               * consequently, will not be made available to
               * reading.
               */
              poolRawPacket(pkt);
            } else {
              RawPacket oldPkt;

              synchronized (pktSyncRoot) {
                oldPkt = this.pkt;
                this.pkt = pkt;
              }
              if (oldPkt != null) {
                /*
                 * Return oldPkt to the pool because it was made
                 * available to reading and it was not read.
                 */
                poolRawPacket(oldPkt);
              }

              if (videoRecorder != null) videoRecorder.recordData(pkt);

              if ((transferHandler != null) && !closed) {
                try {
                  transferHandler.transferData(this);
                } catch (Throwable t) {
                  /*
                   * XXX We cannot allow transferHandler to
                   * kill us.
                   */
                  if (t instanceof ThreadDeath) {
                    throw (ThreadDeath) t;
                  } else {
                    logger.warn("An RTP packet may have not been" + " fully handled.", t);
                  }
                }
              }
            }
          }
        }
        rawPacketArrayPool.offer(pkts);
      }
    }
  }
コード例 #15
0
  public void runSupport() {
    byte[] input_buffer = new byte[request_dg.getLength()];

    System.arraycopy(request_dg.getData(), 0, input_buffer, 0, input_buffer.length);

    int packet_data_length = input_buffer.length;

    String auth_user = null;
    byte[] auth_user_bytes = null;
    byte[] auth_hash = null;

    if (server.isTrackerPasswordEnabled()) {

      // auth detail should be attached to the packet. Auth details are 16
      // bytes

      if (input_buffer.length < 17) {

        Logger.log(
            new LogEvent(
                LOGID,
                LogEvent.LT_WARNING,
                "TRTrackerServerProcessorUDP: " + "packet received but authorisation missing"));

        return;
      }

      packet_data_length -= 16;

      auth_user_bytes = new byte[8];

      auth_hash = new byte[8];

      System.arraycopy(input_buffer, packet_data_length, auth_user_bytes, 0, 8);

      int user_len = 0;

      while (user_len < 8 && auth_user_bytes[user_len] != 0) {

        user_len++;
      }

      auth_user = new String(auth_user_bytes, 0, user_len);

      System.arraycopy(input_buffer, packet_data_length + 8, auth_hash, 0, 8);
    }

    DataInputStream is =
        new DataInputStream(new ByteArrayInputStream(input_buffer, 0, packet_data_length));

    try {
      String client_ip_address = request_dg.getAddress().getHostAddress();

      PRUDPPacketRequest request = PRUDPPacketRequest.deserialiseRequest(null, is);

      Logger.log(
          new LogEvent(
              LOGID, "TRTrackerServerProcessorUDP: packet received: " + request.getString()));

      PRUDPPacket reply = null;
      TRTrackerServerTorrentImpl torrent = null;

      if (auth_user_bytes != null) {

        // user name is irrelevant as we only have one at the moment

        // <parg_home> so <new_packet> = <old_packet> + <user_padded_to_8_bytes> + <hash>
        // <parg_home> where <hash> = first 8 bytes of sha1(<old_packet> + <user_padded_to_8> +
        // sha1(pass))
        // <XTF> Yes

        byte[] sha1_pw = null;

        if (server.hasExternalAuthorisation()) {

          try {
            URL resource = new URL("udp://" + server.getHost() + ":" + server.getPort() + "/");

            sha1_pw = server.performExternalAuthorisation(resource, auth_user);

          } catch (MalformedURLException e) {

            Debug.printStackTrace(e);
          }

          if (sha1_pw == null) {

            Logger.log(
                new LogEvent(
                    LOGID,
                    LogEvent.LT_ERROR,
                    "TRTrackerServerProcessorUDP: auth fails for user '" + auth_user + "'"));

            reply = new PRUDPPacketReplyError(request.getTransactionId(), "Access Denied");
          }
        } else {

          sha1_pw = server.getPassword();
        }

        // if we haven't already failed then check the PW

        if (reply == null) {

          SHA1Hasher hasher = new SHA1Hasher();

          hasher.update(input_buffer, 0, packet_data_length);
          hasher.update(auth_user_bytes);
          hasher.update(sha1_pw);

          byte[] digest = hasher.getDigest();

          for (int i = 0; i < auth_hash.length; i++) {

            if (auth_hash[i] != digest[i]) {

              Logger.log(
                  new LogEvent(
                      LOGID,
                      LogEvent.LT_ERROR,
                      "TRTrackerServerProcessorUDP: auth fails for user '" + auth_user + "'"));

              reply = new PRUDPPacketReplyError(request.getTransactionId(), "Access Denied");

              break;
            }
          }
        }
      }

      int request_type = TRTrackerServerRequest.RT_UNKNOWN;

      if (reply == null) {

        if (server.isEnabled()) {

          try {
            int type = request.getAction();

            if (type == PRUDPPacketTracker.ACT_REQUEST_CONNECT) {

              reply = handleConnect(client_ip_address, request);

            } else if (type == PRUDPPacketTracker.ACT_REQUEST_ANNOUNCE) {

              Object[] x =
                  handleAnnounceAndScrape(
                      client_ip_address, request, TRTrackerServerRequest.RT_ANNOUNCE);

              if (x == null) {

                throw (new Exception("Connection ID mismatch"));
              }

              reply = (PRUDPPacket) x[0];
              torrent = (TRTrackerServerTorrentImpl) x[1];

              request_type = TRTrackerServerRequest.RT_ANNOUNCE;

            } else if (type == PRUDPPacketTracker.ACT_REQUEST_SCRAPE) {

              Object[] x =
                  handleAnnounceAndScrape(
                      client_ip_address, request, TRTrackerServerRequest.RT_SCRAPE);

              if (x == null) {

                throw (new Exception("Connection ID mismatch"));
              }

              reply = (PRUDPPacket) x[0];
              torrent = (TRTrackerServerTorrentImpl) x[1];

              request_type = TRTrackerServerRequest.RT_SCRAPE;

            } else {

              reply = new PRUDPPacketReplyError(request.getTransactionId(), "unsupported action");
            }
          } catch (Throwable e) {

            // e.printStackTrace();

            String error = e.getMessage();

            if (error == null) {

              error = e.toString();
            }

            reply = new PRUDPPacketReplyError(request.getTransactionId(), error);
          }
        } else {

          System.out.println("UDP Tracker: replying 'disabled' to " + client_ip_address);

          reply = new PRUDPPacketReplyError(request.getTransactionId(), "UDP Tracker disabled");
        }
      }

      if (reply != null) {

        InetAddress address = request_dg.getAddress();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        DataOutputStream os = new DataOutputStream(baos);

        reply.serialise(os);

        byte[] output_buffer = baos.toByteArray();

        DatagramPacket reply_packet =
            new DatagramPacket(output_buffer, output_buffer.length, address, request_dg.getPort());

        socket.send(reply_packet);

        server.updateStats(request_type, torrent, input_buffer.length, output_buffer.length);
      }

    } catch (Throwable e) {

      Logger.log(new LogEvent(LOGID, "TRTrackerServerProcessorUDP: processing fails", e));
    } finally {

      try {
        is.close();

      } catch (Throwable e) {

      }
    }
  }
コード例 #16
0
  public void run() {

    System.out.println("Server is running!");

    try {
      socket = new DatagramSocket(PORT);
    } catch (SocketException se) {
      System.err.println("Couldn't open socket on port " + PORT);
    }

    System.out.println("Datagram server listening on port " + PORT);

    boolean isRunning = true;

    while (isRunning) {
      try {
        // receive request
        byte[] bufReceive = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bufReceive, bufReceive.length);
        socket.receive(packet);
        String receiveMessage = new String(packet.getData(), 0, packet.getLength());
        System.out.println("Server received: " + receiveMessage);

        // send the response to the client
        Scanner myScanner = new Scanner(receiveMessage);
        myScanner.next();
        MyEvent.incoming = receiveMessage;
        MyEvent.incomingIntx = myScanner.nextInt();
        myScanner.close();
        MyEvent.received();

        try {
          Thread.sleep(10000);
        } catch (Exception e) {
        }

        // MyEvent.stopIt();

        /// send to someone else

        int port = packet.getPort();
        InetAddress address = packet.getAddress();
        String respondMessage =
            "Hello "
                + receiveMessage
                + " at "
                + address
                + ", I received your message on port "
                + port;
        byte[] bufSend = respondMessage.getBytes();

        packet = new DatagramPacket(bufSend, bufSend.length, address, port);
        socket.send(packet);
      } catch (IOException ioe) {
        System.err.println("Error! There was a problem in the server!");
        ioe.printStackTrace();
        isRunning = false;
      }
    }
    socket.close();
  }
コード例 #17
0
  public static void default_fn() throws IOException {
    // Declaring Socket for sending and receiving data
    DatagramSocket skt = null;
    // declaring the fields to be used
    String client_name, movie_name, time, cost, password, reply_string;
    int i, j;
    // assigning the socket a port number
    skt = new DatagramSocket(6789);
    // defining the buffer and its size
    byte[] buffer = new byte[1000];
    while (true) {
      // defining the packet to be received from client
      DatagramPacket request = new DatagramPacket(buffer, buffer.length);

      // receiving the packet
      skt.receive(request);

      // comment on the console
      System.out.println("Data received from client");

      // Thread.sleep(5000);//for error check

      // converting the message to string and then splitting it into fields divided by newline
      // character
      String[] arrayMsg = (new String(request.getData())).split("\n");
      client_name = arrayMsg[1];
      movie_name = arrayMsg[2];
      time = arrayMsg[3];
      cost = "$12";
      password = "******";

      // Composing the reply message by appending start time,cost and password
      reply_string = client_name + "\n" + movie_name + "\n" + time + "\n" + cost + "\n" + password;
      System.out.println(reply_string);
      // Thread.sleep(5000); for error check

      // converting string message to byte
      byte[] sendMsg = (reply_string).getBytes();

      // composing the data packet and sending it to the client's address and the same port the
      // client used
      DatagramPacket reply =
          new DatagramPacket(sendMsg, sendMsg.length, request.getAddress(), request.getPort());

      System.out.println("sending confirmation");

      // Thread.sleep(5000);//for error check

      // writing server log file
      PrintWriter writer = new PrintWriter("server_log.txt", "UTF-8");
      writer.println(client_name);
      writer.println(movie_name);
      writer.println(time);
      writer.close();

      // sending the data packet
      skt.send(reply);
      // Closing the server socket
      skt.close();
    }
  }
コード例 #18
0
ファイル: LeetActive.java プロジェクト: pombredanne/rit
  /** Method to keep the connection alive with the name server */
  public void run() {
    boolean connected = false;
    int ticket = 0;
    int serial = -1;
    int time = 1000;

    DatagramPacket inPack = new DatagramPacket(new byte[1024], 1024);
    DatagramPacket outPack = new DatagramPacket(new byte[1024], 1024);

    ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
    DataInputStream inData;
    DataOutputStream outData = new DataOutputStream(outBuf);

    while (running) {
      if (!connected) { // Thoust ought Register thine self
        try {
          outBuf.reset();
          outData.writeByte(0);
          outData.writeUTF(userName);
          outData.writeInt(portNum);
          outData.flush();
          outPack.setData(outBuf.toByteArray());
          nameServer.send(outPack);
        } catch (IOException e) {
          System.err.println("LeetActive: " + e);
        }
      } else { // Thoust ought Renew thine self
        try {
          outBuf.reset();
          outData.writeByte(2);
          outData.writeInt(ticket);
          outData.flush();
          outPack.setData(outBuf.toByteArray());
          nameServer.send(outPack);
        } catch (IOException e) {
          System.err.println(e);
        }
      }

      // Now we will receive a packet...
      try {
        nameServer.receive(inPack);
        inData = new DataInputStream(new ByteArrayInputStream(inPack.getData()));

        byte type = inData.readByte();

        if (type == 1) { // Twas a ticket packet
          try {
            ticket = inData.readInt();
            if (ticket > -1) { // Make sure its not evil
              connected = true;
            } else {
              connected = false;
            }
            time = inData.readInt();
          } catch (IOException e) {
            System.err.println(e);
          }
        }

        if (type == 5) { // Twas an update packet
          try {
            int s = inData.readInt();
            if (s > serial) { // Make sure its not old
              serial = s;
              int size = inData.readInt();
              ArrayList newList = new ArrayList(size);

              for (int x = 0; x < size; x++) {
                newList.add(
                    new String(
                        "" + inData.readUTF() + "@" + inData.readUTF() + ":" + inData.readInt()));
              }

              if (!newList.equals(hostList)) {
                hostList = newList;
                updated = true;
              }
            }
          } catch (IOException e) {
            System.err.println(e);
          }
        }
      } catch (SocketTimeoutException e) { // Server hates you
        connected = false;
        System.err.println(e);
      } catch (IOException e) {
        System.err.println(e);
      }

      try { // Take a nap
        sleep(time / 4);
      } catch (InterruptedException e) {
      }
    }
  }
コード例 #19
0
  private void setSendPacketAddress(DatagramPacket sendPacket, DatagramPacket receivePacket) {

    // Tell the client to send more data
    sendPacket.setAddress(receivePacket.getAddress());
    sendPacket.setPort(receivePacket.getPort());
  }
コード例 #20
0
  /**
   * Copies the properties of a specific <tt>DatagramPacket</tt> to another <tt>DatagramPacket</tt>.
   * The property values are not cloned.
   *
   * @param src the <tt>DatagramPacket</tt> which is to have its properties copied to <tt>dest</tt>
   * @param dest the <tt>DatagramPacket</tt> which is to have its properties set to the value of the
   *     respective properties of <tt>src</tt>
   */
  public static void copy(DatagramPacket src, DatagramPacket dest) {
    synchronized (dest) {
      dest.setAddress(src.getAddress());
      dest.setPort(src.getPort());

      byte[] srcData = src.getData();

      if (srcData == null) dest.setLength(0);
      else {
        byte[] destData = dest.getData();

        if (destData == null) dest.setLength(0);
        else {
          int destOffset = dest.getOffset();
          int destLength = destData.length - destOffset;
          int srcLength = src.getLength();

          if (destLength >= srcLength) destLength = srcLength;
          else if (logger.isLoggable(Level.WARNING)) {
            logger.log(Level.WARNING, "Truncating received DatagramPacket data!");
          }
          System.arraycopy(srcData, src.getOffset(), destData, destOffset, destLength);
          dest.setLength(destLength);
        }
      }
    }
  }
コード例 #21
0
  public void run() {
    while (listen) {
      try {
        byte[] buf = new byte[256];
        byte[] buf2 = new byte[256];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        InetAddress address;
        socket.receive(packet);
        String in = new String(packet.getData(), 0, packet.getLength());
        address = packet.getAddress();
        int port = packet.getPort();
        // newClient = findPort(port, address, newClient);
        String name = findPerson(port, address);
        // System.out.println(name);
        if (in.startsWith("1")) {
          String nama = new String(packet.getData(), 0, packet.getLength());
          nama = nama.substring(1);
          newClient = new Client(packet.getAddress(), packet.getPort(), nama);
          threads.add(newClient);
          String wel =
              "\nWelcome "
                  + newClient.nama
                  + "\n "
                  + "to quit type \"bye\" and to whisper use prefix @name : ";
          buf = (wel).getBytes();
          packet = new DatagramPacket(buf, buf.length, packet.getAddress(), packet.getPort());
          socket.send(packet);
          wel = " enters the room";
          buf = (newClient.nama + wel).getBytes();
          Broadcast(address, port, buf);
        } else if (in.startsWith("@")) {
          // findPort(port, address, newClient);
          Whisper(newClient, packet.getData());
        } else if (in.equals("bye")) {

          String bye = name + " is leaving";
          buf2 = bye.getBytes();
          // packet = new DatagramPacket(buf,buf.length,newClient.address, newClient.port);
          Broadcast(address, port, buf2);

        } else {
          byte[] buf3 = new byte[256];
          String text =
              name + "<broadcast> : " + new String(packet.getData(), 0, packet.getLength());
          buf3 = text.getBytes();
          Broadcast(packet.getAddress(), packet.getPort(), buf3);
        }
      } catch (IOException ex) {
        Logger.getLogger(DatagramServer.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    socket.close();
  }
コード例 #22
0
ファイル: UDP.java プロジェクト: NZDIS/jgroups
  public void run() {
    DatagramPacket packet;
    byte receive_buf[] = new byte[65535];
    int len;
    byte[] tmp, data;

    // moved out of loop to avoid excessive object creations (bela March 8 2001)
    packet = new DatagramPacket(receive_buf, receive_buf.length);

    while (mcast_receiver != null && mcast_sock != null) {
      try {
        packet.setData(receive_buf, 0, receive_buf.length);
        mcast_sock.receive(packet);
        len = packet.getLength();
        data = packet.getData();
        if (len == 1 && data[0] == 0) {
          if (Trace.debug) {
            Trace.info("UDP.run()", "received dummy packet");
          }
          continue;
        }

        if (len == 4) { // received a diagnostics probe
          if (data[0] == 'd' && data[1] == 'i' && data[2] == 'a' && data[3] == 'g') {
            handleDiagnosticProbe(packet.getAddress(), packet.getPort());
            continue;
          }
        }

        if (Trace.debug) {
          Trace.info(
              "UDP.receive()",
              "received (mcast) "
                  + packet.getLength()
                  + " bytes from "
                  + packet.getAddress()
                  + ":"
                  + packet.getPort()
                  + " (size="
                  + len
                  + " bytes)");
        }
        if (len > receive_buf.length) {
          Trace.error(
              "UDP.run()",
              "size of the received packet ("
                  + len
                  + ") is bigger than "
                  + "allocated buffer ("
                  + receive_buf.length
                  + "): will not be able to handle packet. "
                  + "Use the FRAG protocol and make its frag_size lower than "
                  + receive_buf.length);
        }

        if (Version.compareTo(data) == false) {
          Trace.warn(
              "UDP.run()",
              "packet from "
                  + packet.getAddress()
                  + ":"
                  + packet.getPort()
                  + " has different version ("
                  + Version.printVersionId(data, Version.version_id.length)
                  + ") from ours ("
                  + Version.printVersionId(Version.version_id)
                  + "). This may cause problems");
        }

        if (use_incoming_packet_handler) {
          tmp = new byte[len];
          System.arraycopy(data, 0, tmp, 0, len);
          incoming_queue.add(tmp);
        } else {
          handleIncomingUdpPacket(data);
        }
      } catch (SocketException sock_ex) {
        if (Trace.trace) {
          Trace.info("UDP.run()", "multicast socket is closed, exception=" + sock_ex);
        }
        break;
      } catch (InterruptedIOException io_ex) { // thread was interrupted
        ; // go back to top of loop, where we will terminate loop
      } catch (Throwable ex) {
        Trace.error("UDP.run()", "exception=" + ex + ", stack trace=" + Util.printStackTrace(ex));
        Util.sleep(300); // so we don't get into 100% cpu spinning (should NEVER happen !)
      }
    }
    if (Trace.trace) {
      Trace.info("UDP.run()", "multicast thread terminated");
    }
  }
コード例 #23
0
ファイル: C1.java プロジェクト: guneetsinghmehta/CN_project
  public static void main(String args[]) throws InterruptedException, IOException {
    int i, j;
    String serverInetAddress = "localhost";

    String server1AddressString = "10.10.1.1";
    InetAddress server1Address = InetAddress.getByName(server1AddressString);
    String server2AddressString = "10.10.2.2";
    InetAddress server2Address = InetAddress.getByName(server2AddressString);
    String server3AddressString = "10.10.3.2";
    InetAddress server3Address = InetAddress.getByName(server3AddressString);
    String server4AddressString = "localhost";
    InetAddress server4Address = InetAddress.getByName(server4AddressString);

    DatagramSocket skt;
    {
      skt = new DatagramSocket(PORT_NUMBER_CLIENT); // socket used to listen and write
      InetAddress host = InetAddress.getByName(serverInetAddress);
      int serversocket = S1.PORT_NUMBER_SERVER;

      String msg = "Send file size";
      byte[] b = msg.getBytes();

      // dummy assignments - not used anywhere
      int filesize = 1;
      DatagramPacket reply, request;
      reply = new DatagramPacket(b, b.length, host, serversocket);
      request = new DatagramPacket(b, b.length, host, serversocket);

      for (i = 1; i <= 3; i++) {
        // defining a packet called request with parameters b(msg in bytes), b.length, host Internet
        // address and socket number
        if (i == 1) {
          host = server1Address;
        } else if (i == 2) {
          host = server2Address;
        } else if (i == 3) {
          host = server3Address;
        }
        request = new DatagramPacket(b, b.length, host, serversocket);
        // System.out.println("request sent from client to server");
        Thread.sleep(S1.PAUSE_DURATION); // for error checks

        // Sending the packet- for getting the file size
        skt.send(request);

        //		getting reply from
        // server........................................................................................
        byte[] buffer =
            new byte
                [S1.PACKET_SIZE]; // apparently the size of data packet at the receiving side needs
                                  // to be bigger than the size of incoming datapacket
        reply = new DatagramPacket(buffer, buffer.length);

        // receiving packet from server - contatining filesize
        skt.receive(reply);
        // System.out.println("Response Received from server");

        // System.out.println("on Client: - filesize= "+new String(reply.getData()));
        filesize = Integer.parseInt(new String(reply.getData()).trim());
        // System.out.println("on Client: - filesize= "+filesize);
        Thread.sleep(S1.PAUSE_DURATION);
      }

      // here the client know the size of the file
      // Find the number of times it must make iterations - dividing filesize by packet_size
      // Request that many packets from server
      String[] buffer_string = new String[BUFFER_SIZE_CLIENT];
      float delay[] = new float[filesize / S1.PACKET_SIZE];
      System.out.println(filesize);
      System.out.println(S1.PACKET_SIZE);
      System.out.println(filesize / S1.PACKET_SIZE);
      Thread.sleep(2000);
      byte[] buffer = new byte[S1.PACKET_SIZE];
      for (i = 0; i < filesize / S1.PACKET_SIZE; i++) {
        if (i % 100 != 0) {
          // System.out.print(" "+i);
        } else {
          System.out.println(" " + i);
        }

        msg = String.valueOf(i);
        b = msg.getBytes();

        if (i % 3 == 0) {
          host = server1Address;
        } else if (i % 3 == 1) {
          host = server2Address;
        } else if (i % 3 == 2) {
          host = server3Address;
        }

        request = new DatagramPacket(b, b.length, host, serversocket);

        skt.send(request);
        delay[i] = System.nanoTime();
        Thread.sleep(10);
        skt.receive(reply);
        delay[i] = System.nanoTime() - delay[i];
        delay[i] = delay[i] / (1000000);
        /*
        if(empty_index<BUFFER_SIZE_CLIENT)
        {
        	buffer_string[empty_index]=new String(reply.getData());
        	empty_index++;
        }
        else
        {
        	for(j=0;j<BUFFER_SIZE_CLIENT-1;j++)
        	{
        		buffer_string[j]=buffer_string[j+1];
        	}
        	buffer_string[BUFFER_SIZE_CLIENT-1]=new String(reply.getData());
        }*/

        // display_buffer(buffer_string);
      }
      Arrays.sort(delay);
      float delay2[] = new float[filesize / S1.PACKET_SIZE];
      for (i = 0; i < delay2.length; i++) {
        delay2[i] = delay[delay.length - i - 1];
      }
      // delay2 stores the array in descending values

      float[] Sk = new float[filesize / S1.PACKET_SIZE];
      Sk[0] = (float) 0.0;

      for (i = 1; i < filesize / S1.PACKET_SIZE; i++) {
        for (j = 1; j <= i; j++) {
          Sk[i] = Sk[i] + delay2[j];
        }
        Sk[i] = Sk[i] / (10 * i);
      }
      make_output(Sk);
      System.out.format(
          "Sk at 2=%f\n,10=%f\n,20=%f\n,100=%f\n and 30000=%f\n ",
          Sk[1], Sk[9], Sk[19], Sk[99], Sk[29999]);
      // display_buffer(buffer_string);
      skt.close();
    }
  }
コード例 #24
0
  private void runOnDtlsTransport(StreamConnector connector) throws IOException {
    DtlsControlImpl dtlsControl = (DtlsControlImpl) getTransportManager().getDtlsControl(this);
    DtlsTransformEngine engine = dtlsControl.getTransformEngine();
    final DtlsPacketTransformer transformer = (DtlsPacketTransformer) engine.getRTPTransformer();

    byte[] receiveBuffer = new byte[SCTP_BUFFER_SIZE];

    if (LOG_SCTP_PACKETS) {
      System.setProperty(
          ConfigurationService.PNAME_SC_HOME_DIR_LOCATION, System.getProperty("java.io.tmpdir"));
      System.setProperty(
          ConfigurationService.PNAME_SC_HOME_DIR_NAME, SctpConnection.class.getName());
    }

    synchronized (this) {
      // FIXME local SCTP port is hardcoded in bridge offer SDP (Jitsi
      // Meet)
      sctpSocket = Sctp.createSocket(5000);
      assocIsUp = false;
      acceptedIncomingConnection = false;
    }

    // Implement output network link for SCTP stack on DTLS transport
    sctpSocket.setLink(
        new NetworkLink() {
          @Override
          public void onConnOut(SctpSocket s, byte[] packet) throws IOException {
            if (LOG_SCTP_PACKETS) {
              LibJitsi.getPacketLoggingService()
                  .logPacket(
                      PacketLoggingService.ProtocolName.ICE4J,
                      new byte[] {0, 0, 0, (byte) debugId},
                      5000,
                      new byte[] {0, 0, 0, (byte) (debugId + 1)},
                      remoteSctpPort,
                      PacketLoggingService.TransportName.UDP,
                      true,
                      packet);
            }

            // Send through DTLS transport
            transformer.sendApplicationData(packet, 0, packet.length);
          }
        });

    if (logger.isDebugEnabled()) {
      logger.debug("Connecting SCTP to port: " + remoteSctpPort + " to " + getEndpoint().getID());
    }

    sctpSocket.setNotificationListener(this);
    sctpSocket.listen();

    // FIXME manage threads
    threadPool.execute(
        new Runnable() {
          @Override
          public void run() {
            SctpSocket sctpSocket = null;
            try {
              // sctpSocket is set to null on close
              sctpSocket = SctpConnection.this.sctpSocket;
              while (sctpSocket != null) {
                if (sctpSocket.accept()) {
                  acceptedIncomingConnection = true;
                  break;
                }
                Thread.sleep(100);
                sctpSocket = SctpConnection.this.sctpSocket;
              }
              if (isReady()) {
                notifySctpConnectionReady();
              }
            } catch (Exception e) {
              logger.error("Error accepting SCTP connection", e);
            }

            if (sctpSocket == null && logger.isInfoEnabled()) {
              logger.info(
                  "SctpConnection " + getID() + " closed" + " before SctpSocket accept()-ed.");
            }
          }
        });

    // Notify that from now on SCTP connection is considered functional
    sctpSocket.setDataCallback(this);

    // Setup iceSocket
    DatagramSocket datagramSocket = connector.getDataSocket();
    if (datagramSocket != null) {
      this.iceSocket = new IceUdpSocketWrapper(datagramSocket);
    } else {
      this.iceSocket = new IceTcpSocketWrapper(connector.getDataTCPSocket());
    }

    DatagramPacket rcvPacket = new DatagramPacket(receiveBuffer, 0, receiveBuffer.length);

    // Receive loop, breaks when SCTP socket is closed
    try {
      do {
        iceSocket.receive(rcvPacket);

        RawPacket raw =
            new RawPacket(rcvPacket.getData(), rcvPacket.getOffset(), rcvPacket.getLength());

        raw = transformer.reverseTransform(raw);
        // Check for app data
        if (raw == null) continue;

        if (LOG_SCTP_PACKETS) {
          LibJitsi.getPacketLoggingService()
              .logPacket(
                  PacketLoggingService.ProtocolName.ICE4J,
                  new byte[] {0, 0, 0, (byte) (debugId + 1)},
                  remoteSctpPort,
                  new byte[] {0, 0, 0, (byte) debugId},
                  5000,
                  PacketLoggingService.TransportName.UDP,
                  false,
                  raw.getBuffer(),
                  raw.getOffset(),
                  raw.getLength());
        }

        // Pass network packet to SCTP stack
        sctpSocket.onConnIn(raw.getBuffer(), raw.getOffset(), raw.getLength());
      } while (true);
    } finally {
      // Eventually, close the socket although it should happen from
      // expire().
      synchronized (this) {
        assocIsUp = false;
        acceptedIncomingConnection = false;
        if (sctpSocket != null) {
          sctpSocket.close();
          sctpSocket = null;
        }
      }
    }
  }
コード例 #25
0
  public static void main(String args[]) throws Exception {
    DatagramSocket r_clients = null, s_clients = null;
    MulticastSocket servers = null, b_clients = null;

    local = Integer.parseInt(args[1]);
    rec = Integer.parseInt(args[0]);

    System.out.println("Recieving arp on port " + rec + "...");
    System.out.println("Recieving reply arp on port " + (rec + 1) + "...");
    System.out.println("\nEmulating gateway on port " + local + "\nWaiting...");

    try {
      r_clients = new DatagramSocket(rec);

      s_clients = new DatagramSocket(rec + 1);

      b_clients = new MulticastSocket(local);
      b_clients.joinGroup(InetAddress.getByName(group));

      servers = new MulticastSocket(serv_port);
      servers.joinGroup(InetAddress.getByName(group));

      servers.setSoTimeout(10);
      s_clients.setSoTimeout(10);
      b_clients.setSoTimeout(10);
      r_clients.setSoTimeout(10);
    } catch (Exception e) {
      System.out.println("error: " + e.toString());
      System.exit(1);
    }

    byte arp_buf[] = new byte[28];
    DatagramPacket arp_packet = new DatagramPacket(arp_buf, arp_buf.length);

    while (true) {
      try {
        servers.receive(arp_packet);
        System.out.println("\nGot arp from servers");

        System.out.println("Sending arp to local computers");
        arp_packet.setAddress(InetAddress.getByName(group));
        arp_packet.setPort(local);
        try {
          b_clients.send(arp_packet, (byte) 255);
        } catch (Exception e3) {
        }
      } catch (Exception e) {
        try {
          r_clients.receive(arp_packet);
          System.out.println("\nGot arp from client");

          System.out.println("Sending ARP");
          arp_packet.setAddress(InetAddress.getByName(group));
          arp_packet.setPort(serv_port);
          try {
            servers.send(arp_packet, (byte) 255);
          } catch (Exception e3) {
          }
        } catch (Exception e2) {
          try {
            s_clients.receive(arp_packet);
            System.out.println("\nGot reply arp from client");

            arp_packet.setAddress(InetAddress.getByName(group));
            arp_packet.setPort(2500);
            try {
              s_clients.send(arp_packet);
            } catch (Exception e3) {
            }
          } catch (Exception e4) {
          }
        }
      }
    }
  }