コード例 #1
1
ファイル: FortuneServer1.java プロジェクト: suzp1984/parrot
  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();
      }
    }
  }
コード例 #2
0
ファイル: Usr.java プロジェクト: qoopooh/try_git
  public static List<Usr> getList() throws IOException {
    byte[] host_ip = InetAddress.getLocalHost().getAddress();
    DatagramSocket serverSocket = new DatagramSocket(UDP_PORT);
    byte[] buf = BROADCAST_MSG.getBytes();
    InetAddress address = InetAddress.getByName(ALL_IP);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, UDP_PORT);
    serverSocket.send(packet);
    serverSocket.setSoTimeout(SOCKET_TIMEOUT); // set the timeout in millisecounds.

    ArrayList<Usr> out = new ArrayList<Usr>();
    while (true) {
      try {
        byte[] rcv = new byte[32];
        packet = new DatagramPacket(rcv, rcv.length);
        serverSocket.receive(packet);
        byte[] ip = packet.getAddress().getAddress();
        if (Arrays.equals(ip, host_ip)) continue;
        Usr usr = new Usr(packet.getData());
        out.add(usr);
      } catch (SocketTimeoutException e) {
        break;
      }
    }

    serverSocket.close();
    return out;
  }
コード例 #3
0
  public void run() {
    while (true) {
      try {
        DatagramSocket ClientSoc = new DatagramSocket(ClinetPortNumber);
        String Command = "GET";

        byte Sendbuff[] = new byte[1024];
        Sendbuff = Command.getBytes();

        InetAddress ServerHost = InetAddress.getLocalHost();
        ClientSoc.send(new DatagramPacket(Sendbuff, Sendbuff.length, ServerHost, 5217));

        byte Receivebuff[] = new byte[1024];
        DatagramPacket dp = new DatagramPacket(Receivebuff, Receivebuff.length);
        ClientSoc.receive(dp);

        NewsMsg = new String(dp.getData(), 0, dp.getLength());
        System.out.println(NewsMsg);
        lblNewsHeadline.setText(NewsMsg);

        Thread.sleep(5000);
        ClientSoc.close();
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
コード例 #4
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();
  }
コード例 #5
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();
    }
  }
コード例 #6
0
ファイル: GBNSender.java プロジェクト: ralenmandao/ojt
    public void run() {

      while (!isThreadRunning) {

        byte[] ack_byte = new byte[2];

        DatagramPacket packet_ack = new DatagramPacket(ack_byte, ack_byte.length);
        try {
          socketAck.setSoTimeout(5);
        } catch (SocketException e) {
          e.printStackTrace();
        }
        try {
          socketAck.receive(packet_ack);
        } catch (IOException e) {
          e.printStackTrace();
        }
        byte[] ackData = packet_ack.getData();
        int packet_ack_num = getAckPaket(ackData);
        num_acked = Math.max(num_acked, packet_ack_num);
        Thread.yield();
      }

      socketAck.close();
    }
コード例 #7
0
  public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      System.err.println("Usage: java RFS862_UdpClient <destination host> <destination port>");
      System.exit(1);
    }
    // get the dest host + port from console
    String dest_host = args[0];
    int dest_port = Integer.parseInt(args[1]);

    // input stream from the console
    BufferedReader inFromUserConsole = new BufferedReader(new InputStreamReader(System.in));
    // new udp socket
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress IPAddress = InetAddress.getByName(dest_host);
    // sizes of sent and received data
    byte[] sendData = new byte[1024];
    byte[] receiveData = new byte[1024];
    // the message from the client
    System.out.println("Please input a message:");
    String sentence = inFromUserConsole.readLine();

    sendData = sentence.getBytes();
    // build the datagram package
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, dest_port);
    // send it to the server
    clientSocket.send(sendPacket);
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    // get data from the server
    clientSocket.receive(receivePacket);
    // cast the received message as string
    String modifiedSentence = new String(receivePacket.getData());
    System.out.println(modifiedSentence);
    // close the client socket
    clientSocket.close();
  }
コード例 #8
0
ファイル: MockClient.java プロジェクト: kcorman/cse461
  private void getAndSendInitialInfo() {
    byte[] idBuf = new byte[4];
    ByteBuffer buf = ByteBuffer.wrap(idBuf);
    buf.putInt(userid);
    DatagramPacket idPacket = new DatagramPacket(idBuf, idBuf.length);

    byte[] serverAckBuf = new byte[1];
    DatagramPacket serverAckPacket = new DatagramPacket(serverAckBuf, serverAckBuf.length);
    boolean receivedAck = false;
    while (!receivedAck) {
      try {
        ds.setSoTimeout(REG_TIMEOUT);
        System.out.println("CLIENT " + userid + ": attempting to register");
        ds.send(idPacket);
        ds.receive(serverAckPacket);
        receivedAck = true;
        byte indicator = serverAckBuf[0];
        System.out.println("CLIENT " + userid + ": received ack: " + indicator);
        if (indicator == 0 || indicator == 1) {
          team = indicator;
        } else {
          // server error, must exit
          throw new RuntimeException(
              "Server responded with code: " + indicator + ", will not start.");
        }
      } catch (SocketTimeoutException e) {
        continue;
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    System.out.println("CLIENT:" + userid + " Done registering.");
    // throw new UnsupportedOperationException();
  }
コード例 #9
0
  private static void setupService() {
    try {
      // setup webserver to listen on localhost:80
      Webserver server = new Webserver(80);

      // open broadcast socket on port 15000
      DatagramSocket broadcast_socket = new DatagramSocket();
      broadcast_socket.setBroadcast(true);

      // {optional} mac address hash
      String macHash = "12345678909876543212345678909876";
      // get IP address from this machine

      // Create broadcast message
      String broadcast_msg = "Sensor online, MACHash=" + macHash + ", IP=" + getIP();
      // Create broadcast packet
      DatagramPacket broadcast_packet =
          new DatagramPacket(
              broadcast_msg.getBytes(),
              broadcast_msg.getBytes().length,
              InetAddress.getByName("255.255.255.255"),
              15000);
      // Send Broadcast packet
      broadcast_socket.send(broadcast_packet);

    } catch (IOException ex) {
      Logger.getLogger(UserTrackerApplication.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
コード例 #10
0
ファイル: Arcon.java プロジェクト: prinsessa/Arcon
 // kill it with fire!
 public boolean close() {
   if (!socket.isClosed() || socket.isConnected()) {
     socket.close();
     return true;
   }
   return false;
 }
コード例 #11
0
ファイル: ConnectionThread.java プロジェクト: smsesteves/SDIS
  public void run() {

    try {
      // System.out.print(mcastaddr.);
      // byte[] b1 = new byte[100] (225,001,001,001);
      InetAddress address = InetAddress.getByName(mcastaddr);
      DatagramSocket s = new DatagramSocket();
      // s.connect(address, Integer.parseInt(mcastport));

      byte[] message = new byte[1024];

      String address1 = InetAddress.getLocalHost().getHostAddress();
      message = (address1 + ":" + port).getBytes();

      DatagramPacket mp =
          new DatagramPacket(message, message.length, address, Integer.parseInt(mcastport));
      s.send(mp);

      Thread.sleep(10000);

    } catch (UnknownHostException | NumberFormatException | SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #12
0
ファイル: UDPClient.java プロジェクト: magnlun/cnt
  public static void main(final String... args) throws Throwable {
    final String remotehost = args[0];
    final int remoteport = Integer.parseInt(args[1]);
    final DatagramSocket socket = new DatagramSocket();

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

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

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

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

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

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

      socket.send(new DatagramPacket(buffer, ptr, remote));
    }
  }
コード例 #13
0
  private void btnEncerrarActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnEncerrarActionPerformed
    // TODO add your handling code here:
    LoginVO lvo = LoginVO.getInstancia();
    DatagramSocket conexao = null;

    try {
      String mensagem = "1_2_";

      conexao = new DatagramSocket();
      byte[] m = mensagem.getBytes();

      InetAddress aHost = InetAddress.getByName(lvo.getIpServidor());
      int serverPort = 1970;

      System.out.println("ENVIOU: " + mensagem);

      DatagramPacket request = new DatagramPacket(m, m.length, aHost, serverPort);
      conexao.send(request);

      this.dispose();
    } catch (IOException e) {
      System.out.println("IOException: " + e);
    }
  } // GEN-LAST:event_btnEncerrarActionPerformed
コード例 #14
0
 /** Accept incoming events and processes them. */
 @Override
 public void run() {
   while (isActive()) {
     if (datagramSocket.isClosed()) {
       // OK we're done.
       return;
     }
     try {
       final byte[] buf = new byte[maxBufferSize];
       final DatagramPacket packet = new DatagramPacket(buf, buf.length);
       datagramSocket.receive(packet);
       final ByteArrayInputStream bais =
           new ByteArrayInputStream(packet.getData(), packet.getOffset(), packet.getLength());
       logEventInput.logEvents(logEventInput.wrapStream(bais), this);
     } catch (final OptionalDataException e) {
       if (datagramSocket.isClosed()) {
         // OK we're done.
         return;
       }
       logger.error("OptionalDataException eof=" + e.eof + " length=" + e.length, e);
     } catch (final EOFException e) {
       if (datagramSocket.isClosed()) {
         // OK we're done.
         return;
       }
       logger.info("EOF encountered");
     } catch (final IOException e) {
       if (datagramSocket.isClosed()) {
         // OK we're done.
         return;
       }
       logger.error("Exception encountered on accept. Ignoring. Stack Trace :", e);
     }
   }
 }
コード例 #15
0
ファイル: NetworkUtils.java プロジェクト: gavinljj/Hive2Hive
  /**
   * checks if a specific port is available.
   *
   * @param port the port to check for availability
   */
  public static boolean isPortAvailable(int port) {
    if (port < 0 || port > 65535) {
      throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException e) {
      return false;
    } finally {
      if (ds != null) {
        ds.close();
      }
      if (ss != null) {
        try {
          ss.close();
        } catch (IOException e) {
          /* should not be thrown */
        }
      }
    }
  }
コード例 #16
0
  /**
   * Checks to see if a specific port is available.
   *
   * @param port the port to check for availability
   * @return <tt>true</tt> if the port is available, <tt>false</tt> otherwise
   */
  public boolean available(int port) {
    if (port < fromPort || port > toPort) {
      throw new IllegalArgumentException("Port outside port range: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException ignored) {
      /* checkstyle drives me nuts */
    } finally {
      if (ds != null) {
        ds.close();
      }

      if (ss != null) {
        try {
          ss.close();
        } catch (IOException ignored) {
          /* checkstyle drives me nuts */
        }
      }
    }

    return false;
  }
コード例 #17
0
  /**
   * 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;
  }
コード例 #18
0
ファイル: Sender.java プロジェクト: jmnx/Learning-OpenCV
  public static void main(String[] args) throws Exception {

    int localPort = 40000;
    int port = 50000;
    String host = "localhost";
    String msg = "Hallo World! Random: " + rndmFromRage(0, 99);

    if (args.length == 4) {
      localPort = Integer.parseInt(args[0]);
      host = args[1];
      port = Integer.parseInt(args[2]);
      msg = args[3];
    }

    System.out.println("(Sender) starting on port: " + localPort);

    try (DatagramSocket socket = new DatagramSocket(localPort)) {

      System.out.println("(Sender) sending: '" + msg + "' to: " + host + ":" + port);

      InetAddress addr = InetAddress.getByName(host);
      DatagramPacket packet = new DatagramPacket(new byte[BUFFER_SIZE], BUFFER_SIZE, addr, port);
      byte[] data = msg.getBytes();
      packet.setData(data);
      packet.setLength(data.length);

      socket.send(packet);
    }
  }
コード例 #19
0
ファイル: BroadCastUdp.java プロジェクト: NinJar/project-K
  public void run() {
    DatagramPacket dataPacket = null;

    try {
      udpSocket = new DatagramSocket(DEFAULT_PORT);

      dataPacket = new DatagramPacket(buffer, MAX_DATA_PACKET_LENGTH);
      byte[] data = dataString.getBytes();
      dataPacket.setData(data);
      dataPacket.setLength(data.length);
      dataPacket.setPort(DEFAULT_PORT);

      InetAddress broadcastAddr;
      String ipAddress = iA.getIpAddress();
      broadcastAddr = InetAddress.getByName(ipAddress);
      dataPacket.setAddress(broadcastAddr);
    } catch (Exception e) {
      Log.e(LOG_TAG, e.toString());
    }
    // while( start ){
    try {
      udpSocket.send(dataPacket);
      sleep(10);
    } catch (Exception e) {
      Log.e(LOG_TAG, e.toString());
    }
    // }

    udpSocket.close();
  }
コード例 #20
0
ファイル: UDP.java プロジェクト: NZDIS/jgroups
  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);
      }
    }
  }
コード例 #21
0
ファイル: RadiusClient.java プロジェクト: seko99/NCC
  /**
   * Sends a Radius packet to the server and awaits an answer.
   *
   * @param request packet to be sent
   * @param port server port number
   * @return response Radius packet
   * @exception RadiusException malformed packet
   * @exception IOException communication error (after getRetryCount() retries)
   */
  public RadiusPacket communicate(RadiusPacket request, int port)
      throws IOException, RadiusException {
    DatagramPacket packetIn =
        new DatagramPacket(
            new byte[RadiusPacket.MAX_PACKET_LENGTH], RadiusPacket.MAX_PACKET_LENGTH);
    DatagramPacket packetOut = makeDatagramPacket(request, port);

    DatagramSocket socket = getSocket();
    for (int i = 1; i <= getRetryCount(); i++) {
      try {
        socket.send(packetOut);
        socket.receive(packetIn);
        return makeRadiusPacket(packetIn, request);
      } catch (IOException ioex) {
        if (i == getRetryCount()) {
          if (logger.isErrorEnabled()) {
            if (ioex instanceof SocketTimeoutException)
              logger.error("communication failure (timeout), no more retries");
            else logger.error("communication failure, no more retries", ioex);
          }
          throw ioex;
        }
        if (logger.isInfoEnabled()) logger.info("communication failure, retry " + i);
        // TODO increase Acct-Delay-Time by getSocketTimeout()/1000
        // this changes the packet authenticator and requires packetOut to be
        // calculated again (call makeDatagramPacket)
      }
    }

    return null;
  }
コード例 #22
0
ファイル: RawSender.java プロジェクト: armanafghani/udp
  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());
      }
    }
  }
コード例 #23
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();
      }
    }
  }
コード例 #24
0
  @Override
  public void run() {
    try {
      socket = new DatagramSocket(port);

      while (!isClosed) {
        if (socket.isClosed()) return;

        byte[] buf = new byte[256];

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

        ByteArrayInputStream bis = new ByteArrayInputStream(buf, 0, packet.getLength());
        BufferedReader in = new BufferedReader(new InputStreamReader(bis));

        String msg;
        while ((msg = in.readLine()) != null) {
          logger.debug("Read from socket: " + msg);
          content.add(msg.trim());
        }
        in.close();
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #25
0
ファイル: MainActivity.java プロジェクト: steinwurf/pulze
    @Override
    public void run() {
      Log.d(TAG, "Starting keep alive...");
      DatagramSocket socket = null;
      try {
        socket = new DatagramSocket(PORT);
        try {
          InetAddress host = InetAddress.getByName(mAddress);
          while (mTransmit) {
            byte[] buffer = {0x66};
            DatagramPacket out = new DatagramPacket(buffer, buffer.length, host, PORT);
            socket.send(out);
            sleep(mInterval);
          }
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

      } catch (SocketException e) {
        e.printStackTrace();
      } finally {
        if (socket != null) {
          socket.close();
        }
      }
    }
コード例 #26
0
ファイル: UDPPinger.java プロジェクト: hidebay/ipscan
  public PingResult ping(ScanningSubject subject, int count) throws IOException {
    PingResult result = new PingResult(subject.getAddress());

    DatagramSocket socket = sockets.bind(new DatagramSocket());
    socket.setSoTimeout(timeout);
    socket.connect(subject.getAddress(), PROBE_UDP_PORT);

    for (int i = 0; i < count && !Thread.currentThread().isInterrupted(); i++) {
      long startTime = System.currentTimeMillis();
      byte[] payload = new byte[8];
      ByteBuffer.wrap(payload).putLong(startTime);
      DatagramPacket packet = new DatagramPacket(payload, payload.length);
      try {
        socket.send(packet);
        socket.receive(packet);
      } catch (PortUnreachableException e) {
        result.addReply(System.currentTimeMillis() - startTime);
      } catch (SocketTimeoutException ignore) {
      } catch (NoRouteToHostException e) {
        // this means that the host is down
        break;
      } catch (SocketException e) {
        if (e.getMessage().contains(/*No*/ "route to host")) {
          // sometimes 'No route to host' also gets here...
          break;
        }
      } catch (IOException e) {
        LOG.log(FINER, subject.toString(), e);
      }
    }
    return result;
  }
コード例 #27
0
 @Override
 public void run() {
   /* Legacy UDP location manager daemon.
    */
   DatagramPacket packet;
   while (!Thread.currentThread().isInterrupted()) {
     try {
       packet = new DatagramPacket(new byte[1024], 1024);
       socket.receive(packet);
     } catch (SocketException e) {
       if (!Thread.currentThread().isInterrupted()) {
         LOGGER.warn("Exception in Server receive loop (exiting)", e);
       }
       break;
     } catch (Exception ie) {
       LOGGER.warn("Exception in Server receive loop (exiting)", ie);
       break;
     }
     try {
       process(packet);
       socket.send(packet);
     } catch (Exception se) {
       LOGGER.warn("Exception in send ", se);
     }
   }
   socket.close();
 }
コード例 #28
0
ファイル: Server.java プロジェクト: oy-attia/RDTProtocol
  public void run() {
    printWelcome();
    while (!welcomingSocket.isClosed()) {
      while (!canCreateNewWorker()) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          continue;
        }
      }

      try {
        DatagramPacket pkt = new DatagramPacket(new byte[EXPECTED_REQ_SIZE], EXPECTED_REQ_SIZE);
        welcomingSocket.receive(pkt); // Blocks!
        RequestPacket reqPkt = new RequestPacket(pkt);

        if (reqPkt.isCorrupted()) {
          continue;
        }

        ConnectionHandler conn = new ConnectionHandler(strategy, reqPkt, plp, pep, rngSeed, maxN);
        Thread connectionHandler = new Thread(conn);
        connectionHandler.start();
        workers.add(new Worker(connectionHandler, conn, System.currentTimeMillis()));
      } catch (IOException e) {
        continue;
      }
    }
  }
コード例 #29
0
  private static boolean available(int port) {
    if (port <= 0) {
      throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
      ss = new ServerSocket(port);
      ss.setReuseAddress(true);
      ds = new DatagramSocket(port);
      ds.setReuseAddress(true);
      return true;
    } catch (IOException e) {
      LogKit.logNothing(e);
    } finally {
      if (ds != null) {
        ds.close();
      }

      if (ss != null) {
        try {
          ss.close();
        } catch (IOException e) {
          // should not be thrown, just detect port available.
          LogKit.logNothing(e);
        }
      }
    }
    return false;
  }
コード例 #30
0
ファイル: Client.java プロジェクト: rgv26/L3_2015_2016
  @SuppressWarnings("empty-statement")
  public static void main(String[] args) {
    InetSocketAddress ia;
    DatagramPacket paquet;
    Scanner sc;
    String s;
    byte[] data;
    int port;

    sc = new Scanner(System.in);

    if (args.length == 1) {
      port = new Integer(args[1]);
    } else {
      System.out.println("Entrez un numero de port entre 0 et 9999");
      while ((port = sc.nextInt()) < 0 || port > 9999) ;
    }

    try (DatagramSocket dso = new DatagramSocket()) {
      s = sc.next() + "\n";
      data = s.getBytes();
      ia = new InetSocketAddress(InetAddress.getLocalHost(), port);
      paquet = new DatagramPacket(data, data.length, ia);
      dso.send(paquet);
    } catch (Exception e) {
    }
  }