Example #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();
  }
Example #2
1
  public void run() {
    if (ServerSocket == null) return;
    while (true) {
      try {
        InetAddress address;
        int port;
        DatagramPacket packet;
        byte[] data = new byte[1460];
        packet = new DatagramPacket(data, data.length);
        ServerSocket.receive(packet);
        //
        //
        address = packet.getAddress();
        port = packet.getPort();
        System.out.println("get the Client port is: " + port);
        System.out.println("get the data length is: " + data.length);

        FileWriter fw = new FileWriter("Fortunes.txt");
        PrintWriter out = new PrintWriter(fw);
        for (int i = 0; i < data.length; i++) {
          out.print(data[i] + "  ");
        }
        out.close();
        System.out.println("Data has been writen to destination!");

        packet = new DatagramPacket(data, data.length, address, port);
        ServerSocket.send(packet);
        System.out.println("Respond has been made!");
      } catch (Exception e) {
        System.err.println("Exception: " + e);
        e.printStackTrace();
      }
    }
  }
Example #3
0
  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();
    }
  }
Example #4
0
  public static void main(String[] args) {
    int port = 5555;

    DatagramSocket socket;
    socket = null;
    try {
      socket = new DatagramSocket(port);
      socket.setBroadcast(true);
      socket.connect(InetAddress.getByName("255.255.255.255"), 5555);
    } catch (Exception e) {
      System.err.println("Connection failed. " + e.getMessage());
    }

    while (true) {
      String message = "hey";
      byte[] buf = message.getBytes();

      DatagramPacket packet = new DatagramPacket(buf, buf.length);
      try {
        socket.send(packet);
      } catch (Exception e) {
        System.err.println("Sending failed. " + e.getMessage());
      }
    }
  }
  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();
  }
Example #6
0
  void setBufferSizes() {
    if (sock != null) {
      try {
        sock.setSendBufferSize(ucast_send_buf_size);
      } catch (Throwable ex) {
        Trace.warn("UDP.setBufferSizes()", "failed setting ucast_send_buf_size in sock: " + ex);
      }
      try {
        sock.setReceiveBufferSize(ucast_recv_buf_size);
      } catch (Throwable ex) {
        Trace.warn("UDP.setBufferSizes()", "failed setting ucast_recv_buf_size in sock: " + ex);
      }
    }

    if (mcast_sock != null) {
      try {
        mcast_sock.setSendBufferSize(mcast_send_buf_size);
      } catch (Throwable ex) {
        Trace.warn(
            "UDP.setBufferSizes()", "failed setting mcast_send_buf_size in mcast_sock: " + ex);
      }

      try {
        mcast_sock.setReceiveBufferSize(mcast_recv_buf_size);
      } catch (Throwable ex) {
        Trace.warn(
            "UDP.setBufferSizes()", "failed setting mcast_recv_buf_size in mcast_sock: " + ex);
      }
    }
  }
Example #7
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();
  }
  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) {

    }
  }
  /**
   * 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;
  }
 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();
   }
 }
  /**
   * Attempts to log a client in using the authentication server. Authentication server needs to run
   * on the same host as the file server.
   *
   * @throws IOException Error reading from socket.
   */
  private void login() throws IOException {
    // set up required variables
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress authServerIP =
        InetAddress
            .getLocalHost(); // because authentication server runs on same host as file server
    byte[] dataToSend;
    byte[] receivedData = new byte[BUFFER_SIZE];

    // get username and password
    String userName = inFromClient.readLine().trim(); // get username
    String password = inFromClient.readLine().trim(); // get password
    dataToSend = new String(userName + " " + password).getBytes();

    // send the username and password for processing by authentication server
    DatagramPacket packetToSend =
        new DatagramPacket(dataToSend, dataToSend.length, authServerIP, AUTHENTICATION_PORT);
    clientSocket.send(packetToSend);

    // receive the response from the authentication server
    DatagramPacket receivedPacket = new DatagramPacket(receivedData, receivedData.length);
    clientSocket.receive(receivedPacket);
    String receivedString = new String(receivedPacket.getData()).trim();
    receivedData = receivedString.getBytes();
    if (receivedString.equals("yes")) {
      outToClient.writeBytes(receivedString); // successful login
    } else {
      outToClient.writeBytes("no"); // unsuccessful login
    }
  }
Example #12
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));
    }
  }
Example #13
0
  public static void doEcho(int port) throws IOException {
    byte[] buf = new byte[BUF_SIZE];
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    DatagramSocket sock = new DatagramSocket(port);

    System.out.println(
        "Starting UDP echo on"
            + sock.getLocalAddress().getHostAddress()
            + ":"
            + sock.getLocalPort());
    while (true) {
      try {
        sock.receive(packet);
        sock.send(packet);
        System.out.print(
            "UDP From: "
                + packet.getAddress().getHostAddress()
                + ":"
                + packet.getPort()
                + "\n"
                + new String(packet.getData(), 0, packet.getLength())
                + "\n");
        System.out.flush();

        packet.setLength(buf.length);
        // packet = new DatagramPacket(buf,buf.length);
      } catch (IOException io_ex) {
      }
    }
  }
Example #14
0
  public void run() {
    System.out.println("ExeUDPServer开始监听..." + UDP_PORT);
    DatagramSocket ds = null;
    try {
      ds = new DatagramSocket(UDP_PORT);
    } catch (BindException e) {
      System.out.println("UDP端口使用中...请重关闭程序启服务器");
    } catch (SocketException e) {
      e.printStackTrace();
    }

    while (ds != null) {
      DatagramPacket dp = new DatagramPacket(buf, buf.length);
      try {
        ds.receive(dp);
        // 得到把该数据包发来的端口和Ip
        int rport = dp.getPort();
        InetAddress addr = dp.getAddress();
        String recvStr = new String(dp.getData(), 0, dp.getLength());
        System.out.println("Server receive:" + recvStr + " from " + addr + "  " + rport);

        // 给客户端回应
        String sendStr = "echo of " + recvStr;
        byte[] sendBuf;
        sendBuf = sendStr.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, rport);
        ds.send(sendPacket);

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Example #15
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);
    }
  }
Example #16
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();
   }
 }
Example #17
0
  /** Generic constructor for the name service interface */
  public LeetActive(String svc_host, int svc_port, int portNum) {

    try {
      nameServer = new DatagramSocket();
      nameServer.setSoTimeout(3000);
      nameServer.connect(InetAddress.getByName(svc_host), svc_port);
    } catch (Exception e) {
      System.err.println("LA " + e);
    }
    this.portNum = portNum;
    hostList = new ArrayList();
  }
Example #18
0
  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");
      }
    }
  }
  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();
  }
Example #20
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();
   }
 }
 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) {
   }
 }
Example #22
0
 public static void main(String[] args) {
   try (DatagramSocket socket = new DatagramSocket(0)) {
     socket.setSoTimeout(10000);
     InetAddress host = InetAddress.getByName(HOSTNAME);
     DatagramPacket request = new DatagramPacket(new byte[1], 1, host, PORT);
     DatagramPacket response = new DatagramPacket(new byte[1024], 1024);
     socket.send(request);
     socket.receive(response);
     String result = new String(response.getData(), 0, response.getLength(), "US-ASCII");
     System.out.println(result);
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
  public static void main(String args[]) throws Exception {
    final int ENOUGH_SIZE = 1024;
    final int SMALL_SIZE = 4;

    boolean isBlocked = true;
    int size = ENOUGH_SIZE;

    if (args.length > 0) {
      int opt = Integer.parseInt(args[0]);
      switch (opt) {
        case 1:
          isBlocked = true;
          size = ENOUGH_SIZE;
          break;
        case 2:
          isBlocked = true;
          size = SMALL_SIZE;
          break;
        case 3:
          isBlocked = false;
          size = ENOUGH_SIZE;
          break;
        case 4:
          isBlocked = false;
          size = SMALL_SIZE;
          break;
      }
    }

    DatagramChannel channel = DatagramChannel.open();
    channel.configureBlocking(isBlocked);
    ByteBuffer buffer = ByteBuffer.allocate(size);
    DatagramSocket socket = channel.socket();
    SocketAddress localAddr = new InetSocketAddress(8000);
    socket.bind(localAddr);

    while (true) {
      System.out.println("开始接收数据报");
      SocketAddress remoteAddr = channel.receive(buffer);
      if (remoteAddr == null) {
        System.out.println("没有接收到数据报");
      } else {
        buffer.flip();
        System.out.println("接收到的数据报的大小为" + buffer.remaining());
      }
      Thread.sleep(500);
    }
  }
  public static void Whisper(Client newClient, byte[] buf) {
    String input = new String(buf, 0, buf.length);
    input = input.substring(1);
    byte[] sendbuff = new byte[256];
    String[] parts = null;
    String text = null;
    String whisperTo = null;

    try {
      parts = input.split(" : ");
      whisperTo = parts[0]; // 004
      // System.out.println(newClient.nama+" "+whisperTo);
      text = parts[1];
    } catch (ArrayIndexOutOfBoundsException e) {
      String notif = "wrong prefix";
      sendbuff = notif.getBytes();
      DatagramPacket packet =
          new DatagramPacket(sendbuff, sendbuff.length, newClient.address, newClient.port);
    }
    String prefix = newClient.nama + " : " + text;
    sendbuff = prefix.getBytes();

    for (Client h : threads) {
      if (h.nama.equals(whisperTo)) {
        DatagramPacket packet = new DatagramPacket(sendbuff, sendbuff.length, h.address, h.port);
        try {
          socket.send(packet);
        } catch (IOException ex) {
          Logger.getLogger(DatagramServer.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
  }
Example #25
0
  public void run() {

    while (true) {

      DatagramPacket msg = new DatagramPacket(new byte[1000], 1000);

      try {

        socket.receive(msg);

      } catch (IOException e) {

      }
      ;

      String container = new String(msg.getData());

      container = container.trim();

      if (container.substring(0, container.indexOf(' ')).equals("vfd"))
        CALM.box.mailAction(container.substring(container.indexOf(' ') + 1, container.length()));
      else if (container.substring(0, container.indexOf(' ')).equals("dfv"))
        CALM.box.mailAction2(container.substring(container.indexOf(' ') + 1, container.length()));
    }
  }
Example #26
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);
        }
      }
    }
  }
Example #27
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();
  }
Example #28
0
  /**
   * Workaround for the problem encountered in certains JDKs that a thread listening on a socket
   * cannot be interrupted. Therefore we just send a dummy datagram packet so that the thread 'wakes
   * up' and realizes it has to terminate. Should be removed when all JDKs support
   * Thread.interrupt() on reads. Uses sock t send dummy packet, so this socket has to be still
   * alive.
   *
   * @param dest The destination host. Will be local host if null
   * @param port The destination port
   */
  void sendDummyPacket(InetAddress dest, int port) {
    DatagramPacket packet;
    byte[] buf = {0};

    if (dest == null) {
      try {
        dest = InetAddress.getLocalHost();
      } catch (Exception e) {
      }
    }

    if (Trace.debug) {
      Trace.info("UDP.sendDummyPacket()", "sending packet to " + dest + ":" + port);
    }
    if (sock == null || dest == null) {
      Trace.warn(
          "UDP.sendDummyPacket()", "sock was null or dest was null, cannot send dummy packet");
      return;
    }
    packet = new DatagramPacket(buf, buf.length, dest, port);
    try {
      sock.send(packet);
    } catch (Throwable e) {
      Trace.error(
          "UDP.sendDummyPacket()",
          "exception sending dummy packet to " + dest + ":" + port + ": " + e);
    }
  }
Example #29
0
 void doSend(byte[] data, InetAddress dest, int port) throws IOException {
   DatagramPacket packet;
   packet = new DatagramPacket(data, data.length, dest, port);
   if (sock != null) {
     sock.send(packet);
   }
 }
Example #30
-1
 public UDPEcho(String host, int port) throws IOException, UnknownHostException {
   this.hostIP = InetAddress.getByName(host);
   this.port = port;
   sock = new DatagramSocket();
   System.out.println("UDP: " + sock.getLocalAddress() + ":" + sock.getLocalPort());
   // sock.connect(hostIP,port);
 }