예제 #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();
  }
예제 #2
0
파일: Host.java 프로젝트: ratminer/TFTP
  public void run() {

    try {
      while (running) {
        byte[] sendClientData = new byte[512];
        byte[] sendServerData = new byte[512];
        byte[] receiveClientData = new byte[512];
        byte[] receiveServerData = new byte[512];

        DatagramPacket receiveClientPacket = receivePacket(receiveClientData, receiveSocket);
        receiveClientPacket.getLength();
        // find port used by client
        int clientPort = receiveClientPacket.getPort();

        DatagramSocket hostSocket = new DatagramSocket();

        sendServerData = receiveClientPacket.getData();
        sendPacket(sendServerData, serverIPAddress, ServerPort, hostSocket);

        DatagramPacket receiveServerPacket = receivePacket(receiveServerData, hostSocket);
        if (receiveServerPacket.getData()[0] == 1) {
          running = false;
        }
        sendClientData = receiveServerPacket.getData();
        sendPacket(sendClientData, clientIPAddress, clientPort, hostSocket);

        hostSocket.close();
      }
      receiveSocket.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #3
0
 public static void main(String args[]) {
   try {
     DatagramSocket d1 = new DatagramSocket(2071);
     DatagramSocket d2 = new DatagramSocket(2081);
     UDPSender s = new UDPSender(d1);
     UDPReceiver r = new UDPReceiver(d2);
     s.t.join();
     r.t.join();
     d1.close();
     d2.close();
   } catch (Exception e) {
   }
 }
 public static void main(String args[]) {
   DatagramSocket aSocket = null;
   try {
     aSocket = new DatagramSocket();
     String stringMsg = "0";
     String prevReply = "0";
     InetAddress aHost =
         InetAddress.getByName("localhost"); // recieve a message from the same computer
     int serverPort = 6789; // agreed port
     while (true) {
       stringMsg = "" + (Integer.parseInt(stringMsg) + 1);
       byte[] message = stringMsg.getBytes();
       DatagramPacket request = new DatagramPacket(message, message.length, aHost, serverPort);
       System.out.printf("Producer: Sending: %s\n", stringMsg);
       aSocket.send(request); // send a message
       byte[] buffer = new byte[1000];
       DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
       aSocket.receive(reply); // wait for a reply
       try {
         Thread.sleep(2000); // have a small waiting period
       } catch (InterruptedException e) {
       }
     }
   } catch (SocketException e) {
     System.out.println("Socket: " + e.getMessage());
   } catch (IOException e) {
     System.out.println("IO: " + e.getMessage());
   } finally {
     if (aSocket != null) aSocket.close();
   }
 }
  /**
   * Tries to obtain a mapped/public address for the specified port (possibly by executing a STUN
   * query).
   *
   * @param dst the destination that we'd like to use this address with.
   * @param port the port whose mapping we are interested in.
   * @return a public address corresponding to the specified port or null if all attempts to
   *     retrieve such an address have failed.
   * @throws IOException if an error occurs while stun4j is using sockets.
   * @throws BindException if the port is already in use.
   */
  public InetSocketAddress getPublicAddressFor(InetAddress dst, int port)
      throws IOException, BindException {
    if (!useStun || (dst instanceof Inet6Address)) {
      logger.debug(
          "Stun is disabled for destination "
              + dst
              + ", skipping mapped address recovery (useStun="
              + useStun
              + ", IPv6@="
              + (dst instanceof Inet6Address)
              + ").");
      // we'll still try to bind though so that we could notify the caller
      // if the port has been taken already.
      DatagramSocket bindTestSocket = new DatagramSocket(port);
      bindTestSocket.close();

      // if we're here then the port was free.
      return new InetSocketAddress(getLocalHost(dst), port);
    }
    StunAddress mappedAddress = queryStunServer(port);
    InetSocketAddress result = null;
    if (mappedAddress != null) result = mappedAddress.getSocketAddress();
    else {
      // Apparently STUN failed. Let's try to temporarily disble it
      // and use algorithms in getLocalHost(). ... We should probably
      // eveng think about completely disabling stun, and not only
      // temporarily.
      // Bug report - John J. Barton - IBM
      InetAddress localHost = getLocalHost(dst);
      result = new InetSocketAddress(localHost, port);
    }
    if (logger.isDebugEnabled())
      logger.debug("Returning mapping for port:" + port + " as follows: " + result);
    return result;
  }
예제 #6
0
  public static void main(String args[]) throws Exception {
    // Making a text file
    String filename =
        "C:\\Users\\S.S. Mehta\\Desktop\\Codes\\ComputerNetworks\\CN_project\\CN_project\\test3.txt";
    makeTextFile(filename);

    // Reading the file and puttin it in buffer
    BufferedReader in = new BufferedReader(new FileReader(filename));
    char[] c1 = new char[PACKET_SIZE];
    c1 = readData(in);
    displayPacket(c1);

    // Step3 - making a socket , makeing a packet with inet address and sending it
    byte[] buffer = new byte[PACKET_SIZE];
    DatagramSocket skt = new DatagramSocket(PORT_NUMBER);
    DatagramPacket request = new DatagramPacket(buffer, buffer.length);

    // stop till you receive
    wait(skt, request);
    System.out.println("On server side \nrequest received from Slient");
    // making a packet with an inet address -
    InetAddress host = InetAddress.getByName("localhost");

    DatagramPacket reply = makePacket(c1, host);

    // Sending reply packet
    System.out.println("Sending reply packet to client");
    Thread.sleep(5000);
    skt.send(reply);

    // closing the socket
    skt.close();
  }
예제 #7
0
  public void run() {

    while (moreQuotes) {
      try {
        byte[] buf = new byte[256];

        // receive request
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet); // containing IP ecc.

        // figure out response
        String dString = null;
        if (in == null) dString = new Date().toString();
        else dString = getNextQuote();
        buf = dString.getBytes();

        // send the response to the client at "address" and "port"
        InetAddress address = packet.getAddress();
        int port = packet.getPort();
        packet = new DatagramPacket(buf, buf.length, address, port);
        socket.send(packet);
      } catch (IOException e) {
        e.printStackTrace();
        moreQuotes = false;
      }
    }
    socket.close();
  }
예제 #8
0
  public void destory() {
    procMsgThd.stop0();
    procMsgThd.interrupt();
    mainThread.interrupt();
    if (group != null) {
      try {
        if (recvSocket instanceof MulticastSocket) {
          ((MulticastSocket) recvSocket).leaveGroup(group);
        }
      } catch (IOException ioe) {
      }
    }

    sendSocket.close();
    recvSocket.close();
  }
예제 #9
0
  public static void main(String args[]) throws Exception {

    String serverHostname = args[0];
    int portNumber = Integer.parseInt(args[1]);

    try {
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

      DatagramSocket clientSocket = new DatagramSocket();

      InetAddress IPAddress = InetAddress.getByName(serverHostname);
      System.out.println("Attempting to connect to " + IPAddress + ") via UDP port " + portNumber);
      System.out.println("Enter \"Quit\" to exit program");

      while (true) {
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];

        System.out.print("Enter Message: ");
        String sentence = inFromUser.readLine();

        if (sentence.equals("Quit")) break;

        sendData = sentence.getBytes();

        System.out.println("Sending data to " + sendData.length + " bytes to server.");
        DatagramPacket sendPacket =
            new DatagramPacket(sendData, sendData.length, IPAddress, portNumber);

        clientSocket.send(sendPacket);

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

        System.out.println("Waiting for return packet");
        clientSocket.setSoTimeout(10000);

        try {
          clientSocket.receive(receivePacket);
          String modifiedSentence = new String(receivePacket.getData());

          InetAddress returnIPAddress = receivePacket.getAddress();

          int port = receivePacket.getPort();

          System.out.println("From server at: " + returnIPAddress + ":" + port);
          System.out.println("Message: " + modifiedSentence);
        } catch (SocketTimeoutException ste) {
          System.out.println("Timeout Occurred: Packet assumed lost");
        }
        System.out.print("\n");
      }

      clientSocket.close();
    } catch (UnknownHostException ex) {
      System.err.println(ex);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
예제 #10
0
파일: Blue.java 프로젝트: wrigh182/udpchat
  public static void main(String args[]) throws Exception {

    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

    DatagramSocket clientSocket = new DatagramSocket();

    InetAddress IPAddress = InetAddress.getByName("192.168.1.16");

    byte[] sendData = new byte[1024];
    byte[] receiveData = new byte[1024];

    String sentence = new String("HELLO");
    sendData = sentence.getBytes();
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
    clientSocket.send(sendPacket);
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    clientSocket.receive(receivePacket);
    sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
    if (sentence.equals("##100##")) {
      System.out.println(sentence + ": Waiting for Red.");
    }
    while (!sentence.equals("##200##")) {
      try {
        receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
      } catch (Exception e) {

      }
    }
    if (sentence.equals("##200##")) {
      System.out.println(sentence + ": Red and Blue are connected");
    }

    while (true) {
      receiveData = new byte[1024];
      receivePacket = new DatagramPacket(receiveData, receiveData.length);

      clientSocket.receive(receivePacket);

      sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());

      if (sentence.equals("##300##")) {
        break;
      }

      System.out.println("RED: " + sentence);

      sentence = inFromUser.readLine();
      sendData = sentence.getBytes();
      sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

      clientSocket.send(sendPacket);
    }
    System.out.println(sentence + ": Disconnected.");
    clientSocket.close();
  }
예제 #11
0
 private void enviar(byte[] frame) {
   try {
     socket.send(new DatagramPacket(frame, frame.length, remaddr, remport));
     // System.out.println("Link envió algo ");
   } catch (IOException e) {
     // throw new NodeException(NodeException.EXCEPCION_ENVIO);
     // System.out.println("Excepcion al enviar");
     socket.close();
   }
 }
예제 #12
0
 static byte[] sendReq(byte abyte0[], int i, String s, int j) throws Exception {
   DatagramSocket datagramsocket = new DatagramSocket(i);
   try {
     datagramsocket.setSoTimeout(30000);
     datagramsocket.send(new DatagramPacket(abyte0, abyte0.length, InetAddress.getByName(s), j));
     byte abyte1[] = new byte[512];
     DatagramPacket datagrampacket = new DatagramPacket(abyte1, abyte1.length);
     datagramsocket.receive(datagrampacket);
     byte abyte2[] = new byte[datagrampacket.getLength()];
     System.arraycopy(datagrampacket.getData(), 0, abyte2, 0, datagrampacket.getLength());
     datagramsocket.close();
     return abyte2;
   } catch (Exception exception) {
     try {
       datagramsocket.close();
     } catch (Exception exception1) {
     }
     throw exception;
   }
 }
예제 #13
0
파일: UDP.java 프로젝트: NZDIS/jgroups
  void closeSocket() {
    if (sock != null) {
      // by sending a dummy packet, the thread will terminate (if it was flagged as stopped before)
      sendDummyPacket(sock.getLocalAddress(), sock.getLocalPort());

      sock.close();
      sock = null;
      if (Trace.trace) {
        Trace.info("UDP.closeSocket()", "socket closed");
      }
    }
  }
예제 #14
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();
  }
예제 #15
0
 private void passFileDescriptor(LocalSocket fdSocket, FileDescriptor tunFD) throws Exception {
   OutputStream outputStream = fdSocket.getOutputStream();
   InputStream inputStream = fdSocket.getInputStream();
   try {
     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 1);
     String request = reader.readLine();
     String[] parts = request.split(",");
     LogUtils.i("current open tcp sockets: " + tcpSockets.size());
     LogUtils.i("current open udp sockets: " + udpSockets.size());
     if ("TUN".equals(parts[0])) {
       fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {tunFD});
       outputStream.write('*');
     } else if ("OPEN UDP".equals(parts[0])) {
       String socketId = parts[1];
       passUdpFileDescriptor(fdSocket, outputStream, socketId);
     } else if ("OPEN TCP".equals(parts[0])) {
       String socketId = parts[1];
       String dstIp = parts[2];
       int dstPort = Integer.parseInt(parts[3]);
       int connectTimeout = Integer.parseInt(parts[4]);
       passTcpFileDescriptor(fdSocket, outputStream, socketId, dstIp, dstPort, connectTimeout);
     } else if ("CLOSE UDP".equals(parts[0])) {
       String socketId = parts[1];
       DatagramSocket sock = udpSockets.get(socketId);
       if (sock != null) {
         udpSockets.remove(socketId);
         sock.close();
       }
     } else if ("CLOSE TCP".equals(parts[0])) {
       String socketId = parts[1];
       Socket sock = tcpSockets.get(socketId);
       if (sock != null) {
         tcpSockets.remove(socketId);
         sock.close();
       }
     } else {
       throw new UnsupportedOperationException("fdsock unable to handle: " + request);
     }
   } finally {
     try {
       inputStream.close();
     } catch (Exception e) {
       LogUtils.e("failed to close input stream", e);
     }
     try {
       outputStream.close();
     } catch (Exception e) {
       LogUtils.e("failed to close output stream", e);
     }
     fdSocket.close();
   }
 }
예제 #16
0
  public void run() {
    while (true) {
      try {
        ByteArrayOutputStream b_out = new ByteArrayOutputStream();
        ObjectOutputStream o_out = new ObjectOutputStream(b_out);
        o_out.writeObject(new BroadcastMessage(username));
        DatagramPacket packet =
            new DatagramPacket(b_out.toByteArray(), b_out.toByteArray().length, group, 6969);
        socket = new DatagramSocket(multicastPort);
        socket.send(packet);
        socket.close();

        // sleep for a while
        try {
          sleep(FIVE_SECONDS);
        } catch (InterruptedException e) {
        }
      } catch (IOException e) {
        e.printStackTrace();
        socket.close();
      }
    }
  }
예제 #17
0
 static void LoadModule(String s, int i, String s1, boolean flag) {
   DatagramSocket datagramsocket = null;
   Object obj = null;
   System.out.println("Loading from " + s + ":" + i);
   try {
     datagramsocket = new DatagramSocket();
     datagramsocket.setSoTimeout(10000);
     InetAddress inetaddress = InetAddress.getByName(s);
     Module module = LoadModule(datagramsocket, inetaddress, i, s1, flag);
     if (module != null) module.write();
   } catch (Exception exception) {
     exception.printStackTrace();
     if (datagramsocket != null)
       try {
         datagramsocket.close();
       } catch (Exception exception2) {
       }
     return;
   }
   try {
     datagramsocket.close();
   } catch (Exception exception1) {
   }
 }
예제 #18
0
파일: UDPClient.java 프로젝트: pgouvas/ssl
  public static void main(String args[]) throws Exception {
    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress IPAddress = InetAddress.getByName("62.38.242.7");
    byte[] sendData = new byte[1024];
    byte[] receiveData = new byte[1024];
    String sentence = inFromUser.readLine();
    sendData = sentence.getBytes();
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9310);
    clientSocket.send(sendPacket);

    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    clientSocket.receive(receivePacket);
    String modifiedSentence = new String(receivePacket.getData());
    System.out.println("FROM SERVER:" + modifiedSentence);
    clientSocket.close();
  }
예제 #19
0
 void run() {
   try {
     // 1. creating a socket to connect to the server
     requestSocket = new DatagramSocket();
     serverAddr = InetAddress.getByName(serverIpAddr);
     registerWithServer();
     receiveInitialBoardStateAndInitializeBoard();
     listenToServer();
   } catch (UnknownHostException unknownHost) {
     System.err.println("You are trying to connect to an unknown host!");
   } catch (IOException ioException) {
     ioException.printStackTrace();
   } finally {
     requestSocket.close();
     System.exit(0);
   }
 }
예제 #20
0
 /**
  * Main method keeps waiting for request and do math operation accordingly
  *
  * @param args
  */
 public static void main(String args[]) {
   DatagramSocket aSocket = null;
   try {
     aSocket = new DatagramSocket(6789);
     byte[] buffer = new byte[1000];
     while (true) {
       DatagramPacket request = new DatagramPacket(buffer, buffer.length);
       aSocket.receive(request);
       // receive byte array of equation and put it in string
       String equation = new String(request.getData());
       String answer = "";
       String[] split = equation.split(" ");
       // parse to integer and calculate
       String op = split[1];
       double var1 = Double.parseDouble(split[0]);
       double var2 = Double.parseDouble(split[2]);
       if (op.equals("+")) {
         answer = Double.toString(var1 + var2);
       } else if (op.equals("-")) {
         answer = Double.toString(var1 - var2);
       } else if (op.toLowerCase().equals("X") || op.toLowerCase().equals("x")) {
         answer = Double.toString(var1 * var2);
       } else if (op.equals("/")) {
         answer = Double.toString(var1 / var2);
       }
       // send answer back
       DatagramPacket reply =
           new DatagramPacket(
               answer.getBytes(),
               (answer.getBytes()).length,
               request.getAddress(),
               request.getPort());
       aSocket.send(reply);
     }
   } catch (SocketException e) {
     System.out.println("Socket: " + e.getMessage());
   } catch (IOException e) {
     System.out.println("IO: " + e.getMessage());
   } finally {
     if (aSocket != null) {
       aSocket.close();
     }
   }
 }
예제 #21
0
  // sends a response to the Client based upon the contents of the receive packet
  private void reply(DatagramPacket receivedPacket) {
    // verify the packet
    byte serverMsg[] = {};
    try {
      Request recReq = new Request(receivedPacket.getData(), receivedPacket.getLength());
      if (!recReq.isValid()) {
        throw new IllegalStateException();
      }
      switch (recReq.getFormat()) {
        case RRQ:
          serverMsg = new byte[] {0, 3, 0, 1};
          break;
        case WRQ:
          serverMsg = new byte[] {0, 4, 0, 0};
          break;
        default:
          throw new IllegalStateException();
      }
    } catch (IllegalStateException e) {
      e.printStackTrace();
      System.exit(1);
    }

    DatagramPacket sendPacket =
        new DatagramPacket(
            serverMsg, serverMsg.length, receivedPacket.getAddress(), receivedPacket.getPort());

    readSendPacket(sendPacket);

    try {
      // Send the datagram packet to the client via the send socket.
      DatagramSocket sendSocket = new DatagramSocket();
      sendSocket.send(sendPacket);
      sendSocket.close();
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
    }

    System.out.println("Server: packet sent.\n");
  }
예제 #22
0
 public static void main(String[] args) {
   if (args.length != 1) System.out.println("This program requires a command line argument.");
   else {
     int port = Integer.parseInt(args[0]);
     final int MAX_LEN = 10;
     // This is the assumed maximum byte length of the datagram to be received.
     try {
       DatagramSocket mySocket = new DatagramSocket(port);
       // instantiates a datagram socket for receiving the data
       byte[] buffer = new byte[MAX_LEN];
       DatagramPacket datagram = new DatagramPacket(buffer, MAX_LEN);
       mySocket.receive(datagram);
       String message = new String(buffer);
       System.out.println(message);
       mySocket.close();
     } // end try
     catch (Exception ex) {
       ex.printStackTrace();
     }
   } // end else
 } // end main
예제 #23
0
  public void run() {

    System.out.println("               -----------------UDP Demo Server-----------------" + "\n\n");

    while (true) {
      try {
        // Create a new socket connection bound to the defined port
        DatagramSocket sock = new DatagramSocket(BROADCAST_PORT);

        System.out.println("Waiting for data on local port: " + sock.getLocalPort());

        // Create a packet to contain incoming data
        byte[] buf = new byte[256];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);

        // Wait for incoming data (receive() is a blocking method)
        sock.receive(packet);

        // Retrieve data from packet and display
        String data = new String(packet.getData());
        int endIndex = data.indexOf(0);
        data = data.substring(0, endIndex);
        int remotePort = packet.getPort();
        System.out.println("Received data from remote port " + remotePort + ":\n" + data);

        // Determine origin of packet and display information
        InetAddress remoteAddress = packet.getAddress();
        System.out.println("Sent from address: " + remoteAddress.getHostAddress());

        // Send back an acknowledgment
        String ack = "RECEIVED " + new Date().toString();
        sock.send(new DatagramPacket(ack.getBytes(), ack.length(), remoteAddress, remotePort));

        sock.close();
      } catch (IOException ioe) {
        System.out.println("Error: IOException - " + ioe.toString());
      }
    }
  }
예제 #24
0
 public void run() {
   while (true) {
     try {
       DatagramSocket ds = new DatagramSocket(local_port);
       while (ds.isBound()) {
         Thread.sleep(50);
         // ds = new DatagramSocket(local_port);
       }
       DatagramPacket packin =
           new DatagramPacket(byte_packet1, byte_packet1.length, ia, getport);
       ds.send(packin);
       ds.close();
       Thread.sleep(5000);
     } catch (SocketException ex) {
       Logger.getLogger(myIP.class.getName()).log(Level.SEVERE, null, ex);
       // System.out.println(ex.getMessage());
     } catch (IOException ex) {
       Logger.getLogger(myIP.class.getName()).log(Level.SEVERE, null, ex);
     } catch (InterruptedException ex) {
       Logger.getLogger(myIP.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
 }
예제 #25
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);
  }
예제 #26
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();
    }
  }
예제 #27
0
 public void stop() throws Exception {
   if (t == null) return;
   t.interrupt();
   server.close();
   t.join();
 }
예제 #28
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();
    }
  }
예제 #29
0
  myIP(int temp_local_port) throws UnknownHostException, SocketException, IOException {
    try {
      local_port = temp_local_port;
      short length_message = 0;
      short temp_short;
      int temp_int;
      byte[] temp_byte = null;

      // STUN Massage Type
      temp_short = 0x0001;
      temp_byte = myFunc.ShortToByte(temp_short);
      data[0] = temp_byte[0];
      data[1] = temp_byte[1];

      // Massage Length
      temp_short = length_message;
      temp_byte = myFunc.ShortToByte(temp_short);
      data[2] = temp_byte[0];
      data[3] = temp_byte[1];

      // Magic Cookie
      temp_int = 0x2112A442;
      temp_byte = myFunc.IntToByte(temp_int);
      data[4] = temp_byte[0];
      data[5] = temp_byte[1];
      data[6] = temp_byte[2];
      data[7] = temp_byte[3];

      // Translation ID
      for (int i = 0; i < 3; i++) {
        temp_int = 12314 + i;
        temp_byte = myFunc.IntToByte(temp_int);
        data[8 + i * 4] = temp_byte[0];
        data[9 + i * 4] = temp_byte[1];
        data[10 + i * 4] = temp_byte[2];
        data[11 + i * 4] = temp_byte[3];
      }

      ia = InetAddress.getByName(STUN_host);
      DatagramSocket ds = new DatagramSocket(local_port);
      DatagramPacket pack = new DatagramPacket(data, data.length, ia, getport);
      for (int i = 0; i < data.length; i++) {
        System.out.println(data[i]);
      }
      ds.send(pack);
      int btlength = 64;
      short Res_type_message = 0,
          Res_length_message = 0,
          Res_atribute_type = 0,
          Res_atribute_length = 0;
      int Res_magic_cookie = 0;
      byte Res_family = 0;
      int Res_port = 0;
      int[] Res_IP = new int[4];
      int[] Res_translationID = new int[3];
      DatagramPacket packet = new DatagramPacket(new byte[btlength], btlength);
      ds.receive(packet);
      byte[] arr = packet.getData();

      temp_byte = new byte[2];
      temp_byte[0] = arr[0];
      temp_byte[1] = arr[1];
      Res_type_message = myFunc.ByteToShort(temp_byte);

      temp_byte = new byte[2];
      temp_byte[0] = arr[2];
      temp_byte[1] = arr[3];
      Res_length_message = myFunc.ByteToShort(temp_byte);

      temp_byte = new byte[4];
      temp_byte[0] = arr[4];
      temp_byte[1] = arr[5];
      temp_byte[2] = arr[6];
      temp_byte[3] = arr[7];
      Res_magic_cookie = myFunc.ByteToInt(temp_byte);

      for (int i = 0; i < 3; i++) {
        temp_byte = new byte[4];
        temp_byte[0] = arr[8 + i * 4];
        temp_byte[1] = arr[9 + i * 4];
        temp_byte[2] = arr[10 + i * 4];
        temp_byte[3] = arr[11 + i * 4];
        Res_translationID[i] = myFunc.ByteToInt(temp_byte);
      }

      temp_byte = new byte[2];
      temp_byte[0] = arr[20];
      temp_byte[1] = arr[21];
      Res_atribute_type = myFunc.ByteToShort(temp_byte);

      temp_byte = new byte[2];
      temp_byte[0] = arr[22];
      temp_byte[1] = arr[23];
      Res_atribute_length = myFunc.ByteToShort(temp_byte);

      Res_family = arr[25]; // IPv4 or IPv6

      temp_byte = new byte[2];
      temp_byte[0] = arr[26];
      temp_byte[1] = arr[27];
      Res_port = myFunc.ByteToShort(temp_byte);

      port = Res_port;

      for (int i = 0; i < 4; i++) {
        Res_IP[i] = Byte.toUnsignedInt(arr[28 + i]);
      }

      IPv4 = Res_IP;
      short indic = 0x0010;
      temp_short = indic;
      temp_byte = myFunc.ShortToByte(temp_short);
      data[0] = temp_byte[0];
      data[1] = temp_byte[1];
      ds.close();
    } catch (IOException e) {
      System.err.println(e);
    }
  }
예제 #30
0
  static Module LoadModule(
      DatagramSocket datagramsocket, InetAddress inetaddress, int i, String s, boolean flag) {
    try {
      Module module = new Module();
      module.Name = s;
      int j = Challenge(datagramsocket, inetaddress, i);
      System.out.print("Sending the get request, file '" + s);
      if (flag) System.out.print(" [beta] ");
      byte abyte0[] = Cmd_Get(s, j, flag);
      datagramsocket.send(new DatagramPacket(abyte0, abyte0.length, inetaddress, i));
      try {
        Thread.sleep(50L);
      } catch (Exception exception2) {
      }
      System.out.print("' ...");
      abyte0 = new byte[256];
      DatagramPacket datagrampacket = new DatagramPacket(abyte0, abyte0.length);
      datagramsocket.receive(datagrampacket);
      System.out.println(" ok ");
      ReqFile reqfile = new ReqFile(abyte0);
      if (!((Req) (reqfile)).legal) {
        System.out.println("Can't download module " + s);
        return null;
      }
      module.Size = reqfile.Size;
      module.Header = reqfile.Header;
      module.Data = new byte[module.Size];
      Module module1 = null;
      try {
        module1 = new Module(s);
      } catch (Exception exception3) {
        module1 = null;
      }
      if (module1 != null && module1.compareHeader(module)) {
        byte abyte1[] = Cmd_Abort("");
        datagramsocket.send(new DatagramPacket(abyte1, abyte1.length, inetaddress, i));
        System.out.println(s + " is already the newest version.");
        return null;
      }
      System.out.print("downloading data");
      int k = 0;
      do {
        byte abyte2[] = Cmd_Next(k);
        datagramsocket.send(new DatagramPacket(abyte2, abyte2.length, inetaddress, i));
        try {
          Thread.sleep(50L);
        } catch (Exception exception4) {
        }
        abyte2 = new byte[16534];
        DatagramPacket datagrampacket1 = new DatagramPacket(abyte2, abyte2.length);

        try {
          datagramsocket.receive(datagrampacket1);
        } catch (InterruptedIOException e) {
          continue;
        }

        ReqBlock reqblock = new ReqBlock(abyte2);
        if (!((Req) (reqblock)).legal) {
          if (!"FINISH".equals(((Req) (reqblock)).Cmd)) throw new Exception("Protocol violation");
          break;
        }
        System.arraycopy(reqblock.Data, 0, module.Data, k, reqblock.Size);
        k += reqblock.Size;
        System.out.print(".");
      } while (true);
      if (k != module.Size) {
        throw new Exception("File size mismatch");
      } else {
        System.out.println("done");
        Module.decode(module.Data, j);
        return module;
      }
    } catch (Exception exception) {
      exception.printStackTrace();
    }
    if (datagramsocket != null)
      try {
        datagramsocket.close();
      } catch (Exception exception1) {
      }
    System.out.println("Can't download module " + s);
    return null;
  }