Ejemplo n.º 1
1
  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();
  }
Ejemplo n.º 2
0
  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));
    }
  }
Ejemplo n.º 3
0
  /*
   * Connect a UDP socket, disconnect it, then send and recv on it.
   * It will fail on Linux if we don't silently bind(2) again at the
   * end of DatagramSocket.disconnect().
   */
  private static void testConnectedUDP(InetAddress addr) throws Exception {
    try {
      DatagramSocket s = new DatagramSocket(0, addr);
      DatagramSocket ss = new DatagramSocket(0, addr);
      System.out.print("\tconnect...");
      s.connect(ss.getLocalAddress(), ss.getLocalPort());
      System.out.print("disconnect...");
      s.disconnect();

      byte[] data = {0, 1, 2};
      DatagramPacket p =
          new DatagramPacket(data, data.length, s.getLocalAddress(), s.getLocalPort());
      s.setSoTimeout(10000);
      System.out.print("send...");
      s.send(p);
      System.out.print("recv...");
      s.receive(p);
      System.out.println("OK");

      ss.close();
      s.close();
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }
Ejemplo n.º 4
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) {

    }
  }
Ejemplo n.º 6
0
 public static void wait(DatagramSocket skt, DatagramPacket request)
     throws IOException, InterruptedException {
   // stop till you receive
   skt.receive(request);
   System.out.println("request received");
   Thread.sleep(2000);
 }
Ejemplo n.º 7
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();
  }
Ejemplo n.º 8
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);
      }
    }
Ejemplo n.º 9
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;
  }
Ejemplo n.º 10
0
 public static void main(String[] args) throws Exception {
   if (args.length == 1) {
     DatagramSocket serverSocket; // The server Socket.
     int rec_port = Integer.parseInt(args[0]); // The port on which the server is listening.
     serverSocket = new DatagramSocket(rec_port);
     while (true) {
       echo("\n");
       echo("Listening on port: " + rec_port);
       byte[] receivedData =
           new byte[1]; // The buffer byte array where the received data is stored.
       DatagramPacket clientRequest =
           new DatagramPacket(receivedData, receivedData.length); // Server Packet.
       serverSocket.receive(clientRequest); // Server listening on specified port.
       Server_Receive cli_Thread = new Server_Receive(serverSocket, clientRequest, receivedData);
       cli_Thread.start(); // Server_Receive thread started.
     }
   } else {
     echo("Enter only port. See README");
   }
 }
Ejemplo n.º 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();
    }
  }
  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();
  }
Ejemplo n.º 13
0
  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();
    }
  }
Ejemplo n.º 14
0
  public static void main(String[] args) throws Exception {
    //////////////////// STAGE A//////////////////////////////////////////
    int portNum = 12235;
    //        InetAddress ip=InetAddress.getLocalHost();
    InetAddress ip = InetAddress.getByName("attu2.cs.washington.edu");

    DatagramSocket sock = new DatagramSocket();

    byte[] response = new byte[HEADER_SIZE + 16];
    String partA = "hello world\0";
    byte[] buf = createBuffer(partA.getBytes(), 0, STEP1);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, ip, portNum);
    sock.send(packet);
    packet = new DatagramPacket(response, response.length);
    sock.receive(packet);
    int[] a2 = partA(response); // putting the 4 ints from server into int[]

    //      for (int i = 0; i < a2.length; i++) {
    //          System.out.println(a2[i]);
    //      }

    ////////////////////// STAGE B////////////////////////////////////////

    int numSent = 0;
    int send = a2[0];
    int len = a2[1];
    portNum = a2[2];
    int secretA = a2[3];
    System.out.println("The secrets:\nA: " + secretA);

    sock.setSoTimeout(500); // .5s

    while (numSent < send) {
      // create packet
      buf = createBuffer(partB(numSent, len), secretA, STEP1);
      packet = new DatagramPacket(buf, buf.length, ip, portNum);
      sock.send(packet);
      // send packet
      try {
        sock.receive(new DatagramPacket(response, response.length));
        numSent++;
        ByteBuffer temp = ByteBuffer.wrap(response);
        checkHeader(temp, 4, secretA, STEP1);
        //              System.out.println(temp.getInt());  // For debug. See if counts up by 1
      } catch (SocketTimeoutException e) {
        // if there's a timeout, try again
        continue;
      }
    }
    response = new byte[HEADER_SIZE + 8]; // 8 bytes -- 2 integers
    sock.receive(new DatagramPacket(response, response.length));
    ByteBuffer bb = ByteBuffer.wrap(response);
    // Header
    checkHeader(bb, 8, secretA, STEP2);

    // reset the port number to the one given
    portNum = bb.getInt();
    int secretB = bb.getInt();
    System.out.println("B: " + secretB);

    // close the UDP socket
    sock.close();

    /////////////////////////// STAGE C///////////////////////////////////
    Socket socket = new Socket(ip, portNum);
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    response = new byte[HEADER_SIZE + 16]; // 4 ints given to us this time
    in.read(response);
    bb = ByteBuffer.wrap(response);
    // Header
    checkHeader(bb, 13, secretB, STEP2);

    // num2 len2 secretC and char c

    numSent = bb.getInt();
    len = bb.getInt();
    int secretC = bb.getInt();
    System.out.println("C: " + secretC);

    // stage d
    byte c = (byte) bb.getChar();
    buf = new byte[len];
    Arrays.fill(buf, c);
    for (int i = 0; i < numSent; i++) {
      byte[] b = createBuffer(buf, secretC, STEP1);
      out.write(b);
    }
    response = new byte[12 + 4]; // one integer. secretD plus header
    in.read(response);
    bb = ByteBuffer.wrap(response);
    checkHeader(bb, 4, secretC, STEP2);

    int secretD = bb.getInt();
    socket.close();
    in.close();
    out.close();
    System.out.println("D: " + secretD);
  }
Ejemplo n.º 15
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();
    }
  }
Ejemplo n.º 16
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);
      }
    }
Ejemplo n.º 17
0
  /** 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) {
      }
    }
  }
Ejemplo n.º 18
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) {
          }
        }
      }
    }
  }