예제 #1
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();
  }
예제 #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);
        }
      }
    }
  }
  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) {

    }
  }
예제 #4
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);
        }
      }
    }
  }
예제 #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
  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;
  }
예제 #7
0
    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);
      }
    }
예제 #8
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");
    }
  }
예제 #9
0
  private void setSendPacketAddress(DatagramPacket sendPacket, DatagramPacket receivePacket) {

    // Tell the client to send more data
    sendPacket.setAddress(receivePacket.getAddress());
    sendPacket.setPort(receivePacket.getPort());
  }
예제 #10
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);
      }
    }
  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) {

      }
    }
  }
예제 #12
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();
    }
  }
  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();
  }