Пример #1
0
    @Override
    public void run() {

      DatagramSocket datagramSocket = null;

      while (isContinueListen) {
        try {
          if (datagramSocket == null) {
            datagramSocket = new DatagramSocket(null);
            datagramSocket.setReuseAddress(true);
            datagramSocket.bind(new InetSocketAddress(listenPort));
            datagramSocket.setReceiveBufferSize(512 * 1024);
          }
          byte[] buffer = new byte[1024 * 1024];
          DatagramPacket udpPacket = new DatagramPacket(buffer, buffer.length);

          datagramSocket.receive(udpPacket);

          LPP.put(udpPacket);
          Logg.e(TAG, "收到2000包");
        } catch (Exception e) {
          e.printStackTrace();
          Logg.e(TAG, "收到2000包 error");
          continue;
        }
      }
      if (datagramSocket != null) {
        datagramSocket.close();
        datagramSocket = null;
      }
    }
  public static void main(String[] args) {

    int port = DEFAULT_PORT;
    try {
      port = Integer.parseInt(args[0]);
    } catch (Exception ex) {
    }

    try {
      DatagramChannel channel = DatagramChannel.open();
      DatagramSocket socket = channel.socket();
      SocketAddress address = new InetSocketAddress(port);
      socket.bind(address);
      ByteBuffer buffer = ByteBuffer.allocateDirect(MAX_PACKET_SIZE);
      while (true) {
        SocketAddress client = channel.receive(buffer);
        buffer.flip();
        System.out.print(client + " says ");
        while (buffer.hasRemaining()) System.out.write(buffer.get());
        System.out.println();
        buffer.clear();
      } // end while
    } // end try
    catch (IOException ex) {
      System.err.println(ex);
    } // end catch
  } // end main
Пример #3
0
 /**
  * Creates a datagram socket, bound to the specified local socket address.
  *
  * <p>If, if the address is <code>null</code>, creates an unbound socket.
  *
  * <p>
  *
  * <p>If there is a security manager, its <code>checkListen</code> method is first called with the
  * port from the socket address as its argument to ensure the operation is allowed. This could
  * result in a SecurityException.
  *
  * @param bindaddr local socket address to bind, or <code>null</code> for an unbound socket.
  * @exception SocketException if the socket could not be opened, or the socket could not bind to
  *     the specified local port.
  * @exception SecurityException if a security manager exists and its <code>checkListen</code>
  *     method doesn't allow the operation.
  * @see SecurityManager#checkListen
  * @since 1.4
  */
 public DatagramSocket(SocketAddress bindaddr) throws SocketException {
   // create a datagram socket.
   createImpl();
   if (bindaddr != null) {
     bind(bindaddr);
   }
 }
 @Override
 public synchronized void bind(SocketAddress addr) throws SocketException {
   super.bind(addr);
   // This method might have been called from the super constructor
   if (this.registry != null) {
     this.registry.registerBinding(this);
   }
 }
Пример #5
0
 /**
  * Creates a UDP transport with optional reusing the address if is currently in timeout state
  * (TIME_WAIT) after the connection is closed.
  *
  * @param udpAddress the local address for sending and receiving of UDP messages.
  * @param reuseAddress if <code>true</code> addresses are reused which provides faster socket
  *     binding if an application is restarted for instance.
  * @throws IOException if socket binding fails.
  * @since 1.7.3
  */
 public DefaultUdpTransportMapping(UdpAddress udpAddress, boolean reuseAddress)
     throws IOException {
   super(udpAddress);
   socket = new DatagramSocket(null);
   socket.setReuseAddress(reuseAddress);
   final SocketAddress addr =
       new InetSocketAddress(udpAddress.getInetAddress(), udpAddress.getPort());
   socket.bind(addr);
 }
Пример #6
0
  public static void main(String[] args) throws IOException {
    byte[] buf = null;
    String msg = null;
    int msgPerSecond = 0;
    /* Try to convert single arguments into Integer */
    try {
      buf = new byte[Integer.valueOf(args[2])];
      msg = randomString(Integer.valueOf(args[3]));
      msgPerSecond = Integer.valueOf(args[4]);
    }
    /* On error give the needed information back as String */
    catch (NumberFormatException ex) {
      System.err.printf(
          "usage: server_name port buffer_size " + "message_length message_per_second\n");
      System.exit(1);
    }

    /* Create socket */
    DatagramSocket datagramSocket = new DatagramSocket(null);

    /* Create local endpoint using bind() */
    SocketAddress localBindPoint = new InetSocketAddress(MYPORT);
    datagramSocket.bind(localBindPoint);

    /* Create remote endpoint */
    SocketAddress remoteBindPoint = new InetSocketAddress(args[0], Integer.valueOf(args[1]));

    /* Create datagram packet for sending message */
    DatagramPacket sendPacket = new DatagramPacket(msg.getBytes(), msg.length(), remoteBindPoint);

    /* Create datagram packet for receiving echoed message */
    DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
    /* Check if more than one message should be send */
    if (msgPerSecond > 1) {
      do {
        /* Timer that messages were send every second */
        try {
          TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
          System.err.printf(e.getStackTrace().toString());
        }

        /* Send and receive multiple messages */
        for (int it = 0; it < msgPerSecond; it++) {
          sendReceive(datagramSocket, msg, sendPacket, receivePacket);
        }
        System.out.printf("---------------------------------------------------\n");

      } while (true);
    }
    /* Send one single message */
    else {
      sendReceive(datagramSocket, msg, sendPacket, receivePacket);
      System.out.printf("------------- single message sent --------------\n");
    }
  }
Пример #7
0
 /**
  * Constructs a datagram socket and binds it to any available port on the local host machine. The
  * socket will be bound to the {@link InetAddress#isAnyLocalAddress wildcard} address, an IP
  * address chosen by the kernel.
  *
  * <p>If there is a security manager, its <code>checkListen</code> method is first called with 0
  * as its argument to ensure the operation is allowed. This could result in a SecurityException.
  *
  * @exception SocketException if the socket could not be opened, or the socket could not bind to
  *     the specified local port.
  * @exception SecurityException if a security manager exists and its <code>checkListen</code>
  *     method doesn't allow the operation.
  * @see SecurityManager#checkListen
  */
 public DatagramSocket() throws SocketException {
   // create a datagram socket.
   createImpl();
   try {
     bind(new InetSocketAddress(0));
   } catch (SocketException se) {
     throw se;
   } catch (IOException e) {
     throw new SocketException(e.getMessage());
   }
 }
 public UDPReceiveThread() {
   try {
     // Creates the socket
     if (socket == null) {
       socket = new DatagramSocket(null);
       socket.setReuseAddress(true);
       socket.setBroadcast(true);
       socket.bind(new InetSocketAddress(8080));
     }
   } catch (SocketException e) {
     e.printStackTrace();
   }
 }
Пример #9
0
  private void start() throws SocketException {
    byte[] buf = new byte[BUFSIZE];

    /* Create socket */
    DatagramSocket socket = new DatagramSocket(null);

    /* Create local bind point */
    SocketAddress localBindPoint = new InetSocketAddress(TFTPPORT);
    socket.bind(localBindPoint);

    System.out.printf("Listening at port %d for new requests\n", TFTPPORT);

    while (true) {
        /* Loop to handle various requests */
      final InetSocketAddress clientAddress = receiveFrom(socket, buf);
      if (clientAddress == null) /* If clientAddress is null, an error occurred in receiveFrom()*/
        continue;

      final StringBuffer requestedFile = new StringBuffer();
      final int reqtype = ParseRQ(buf, requestedFile);

      new Thread() {
        public void run() {
          try {
            DatagramSocket sendSocket = new DatagramSocket(0);
            sendSocket.connect(clientAddress);

            System.out.printf(
                "%s request for %s from %s using port %d\n",
                (reqtype == OP_RRQ) ? "Read" : "Write",
                requestedFile.toString(),
                clientAddress.getHostName(),
                clientAddress.getPort());

            if (reqtype == OP_RRQ) {
                /* read request */
              requestedFile.insert(0, READDIR);
              HandleRQ(sendSocket, requestedFile.toString(), OP_RRQ);
            } else {
                /* write request */
              requestedFile.insert(0, WRITEDIR);
              HandleRQ(sendSocket, requestedFile.toString(), OP_WRQ);
            }
            sendSocket.close();
          } catch (SocketException e) {
            e.printStackTrace();
          }
        }
      }.start();
    }
  } // start
  public static void main(String[] args) throws Exception {
    DatagramChannel dc = DatagramChannel.open();
    DatagramSocket socket = dc.socket();
    socket.bind(new InetSocketAddress(22500));
    ByteBuffer byteBuf = ByteBuffer.allocate(8);
    //        byteBuf.order(ByteOrder.LITTLE_ENDIAN);
    LongBuffer longBuf = byteBuf.asLongBuffer();

    while (true) {
      dc.receive(byteBuf);
      System.out.println(longBuf.get(0));
      byteBuf.clear();
    }
  }
Пример #11
0
    // @Override
    // protected void onPreExecute() {
    //     Log.i("AsyncTask", "onPreExecute");
    // }
    @Override
    protected Boolean doInBackground(Void... params) {
      Log.i("AsyncTask", "doInBackground: Creating socket");

      while (networkConnection == true) {
        try {

          DatagramSocket client_socket = new DatagramSocket(null);
          client_socket.setReuseAddress(true);
          client_socket.setBroadcast(true);
          client_socket.bind(new InetSocketAddress(PORT));
          byte[] receiveData = new byte[1024];
          DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
          client_socket.receive(packet);
          modifiedSentence = new String(packet.getData(), 0, packet.getLength());
          Log.i("dostaje dane postaci", modifiedSentence);
          /*String pierwszy = Character.toString(modifiedSentence.charAt(0));
          Log.i("pierwszy znak to", pierwszy);*/

          t.start();

          u.start();

          client_socket.close();

        } catch (Throwable e) {
          e.printStackTrace();
        }

        // setUpMap();

        /*if (modifiedSentence.startsWith("$")) {
                    Log.i("parsuje", "nmee");
                    nmeaParser=new NmeaParser(modifiedSentence);
                    lat=nmeaParser.latitude;
                    lon=nmeaParser.longitude;
                    setUpMap();
                } else {
                    sensor.setTxtaccel_x();
                    sensor.setTxtaccel_y();
                    sensor.setTxtaccel_z();
                    sensor.setTxtmac_id();
                    sensor.setTxtid();
                    Log.d("set text", "dziala");
        }*/
      }

      return true;
    }
  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);
    }
  }
Пример #13
0
 public static void sendTo(String ip, int port, byte[] sendBuf) {
   try {
     if (_client == null) {
       _client = new DatagramSocket(null);
       _client.setReuseAddress(true);
       _client.setBroadcast(true); // 设置标志,T OR E OR R广播数据报
       // 在2.2左右版本不行。在4.0版本上可行
       _client.bind(new InetSocketAddress(port));
     }
     InetAddress address = InetAddress.getByName(ip);
     DatagramPacket sendpacket = new DatagramPacket(sendBuf, SEND_LENGHT, address, port);
     _client.setSoTimeout(2000);
     _client.send(sendpacket);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Пример #14
0
 public static void main(String[] args) throws IOException, InterruptedException {
   DatagramChannel channel = DatagramChannel.open();
   DatagramSocket socket = channel.socket();
   SocketAddress localAddr = new InetSocketAddress(7000);
   SocketAddress remoteAddr = new InetSocketAddress(InetAddress.getByName("localhost"), 8000);
   socket.bind(localAddr);
   while (true) {
     ByteBuffer buffer = ByteBuffer.allocate(1024);
     buffer.clear();
     System.out.println("缓冲区的剩余字节为:" + buffer.remaining());
     buffer.put("send message".getBytes());
     buffer.flip();
     int n = channel.send(buffer, remoteAddr);
     System.out.println("发送的字节数为" + n);
     Thread.sleep(500);
   }
 }
Пример #15
0
 // ------------------------------------------------------------
 @Override
 public void run() {
   DatagramSocket ds;
   int numServers = Integer.valueOf(rb.getString("NumServers"));
   ServerDescription[] validServers = new ServerDescription[numServers];
   int expectedServers = 0;
   boolean addToFile = false, serverAdded;
   System.out.println("Started listening for subagent broadcasts");
   for (int i = 0; i < numServers; i++) validServers[i] = new ServerDescription();
   try {
     expectedServers = getExpectedServers(validServers);
   } catch (GenericException e) {
     System.out.println("Parse error in file, rejecting subagent");
   }
   int listenPort = Integer.valueOf(rb.getString("broadcastPort"));
   System.out.println("listen Port is " + listenPort);
   try {
     ds = new DatagramSocket(null);
     ds.setBroadcast(true);
     ds.setReuseAddress(true);
     ds.bind(new InetSocketAddress(listenPort));
   } catch (IOException e) {
     System.out.println("Error, broadcast socket not created successfully");
     System.out.println("Got message: " + e);
     return;
   }
   byte[] receiveData = new byte[1024];
   DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
   while (keepRunning) {
     try {
       ds.receive(receivePacket);
       System.out.println("Received a datagram packet");
       if (expectedServers < numServers) addToFile = true;
       else addToFile = false;
       serverAdded = respondToDatagram(receivePacket, validServers, addToFile, expectedServers);
       if (serverAdded) expectedServers++;
     } catch (IOException e) {
       System.out.println("Error, unable to connect with subagent");
       System.out.println("Got message: " + e);
     }
   } // end while (keepRunning)
 }
  /**
   * {@collect.stats} {@description.open} Connects this socket to a remote socket address (IP
   * address + port number). Binds socket if not already bound.
   *
   * <p>{@description.close}
   *
   * @param addr The remote address.
   * @param port The remote port
   * @throws SocketException if binding the socket fails.
   */
  private synchronized void connectInternal(InetAddress address, int port) throws SocketException {
    if (port < 0 || port > 0xFFFF) {
      throw new IllegalArgumentException("connect: " + port);
    }
    if (address == null) {
      throw new IllegalArgumentException("connect: null address");
    }
    checkAddress(address, "connect");
    if (isClosed()) return;
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
      if (address.isMulticastAddress()) {
        security.checkMulticast(address);
      } else {
        security.checkConnect(address.getHostAddress(), port);
        security.checkAccept(address.getHostAddress(), port);
      }
    }

    if (!isBound()) bind(new InetSocketAddress(0));

    // old impls do not support connect/disconnect
    if (oldImpl) {
      connectState = ST_CONNECTED_NO_IMPL;
    } else {
      try {
        getImpl().connect(address, port);

        // socket is now connected by the impl
        connectState = ST_CONNECTED;
      } catch (SocketException se) {

        // connection will be emulated by DatagramSocket
        connectState = ST_CONNECTED_NO_IMPL;
      }
    }

    connectedAddress = address;
    connectedPort = port;
  }
Пример #17
0
  /**
   * 获取设备信息
   *
   * @param msg
   * @param listener
   */
  public static void receive(String msg, UdpCallBackListener listener) {
    ArrayList<String> responses = new ArrayList<String>();
    String Strs = "";
    try {
      if (_client == null) {
        _client = new DatagramSocket(null);
        _client.setReuseAddress(true);
        _client.setBroadcast(true); // 设置标志,T OR E OR R广播数据报
        // 在2.2左右版本不行。在4.0版本上可行
        _client.bind(new InetSocketAddress(port));
      }
      DatagramPacket sendDp =
          new DatagramPacket(
              msg.getBytes(), msg.getBytes().length, InetAddress.getByName(IP), port);
      _client.setSoTimeout(2000);
      _client.send(sendDp);
      byte[] buf = new byte[1024];
      DatagramPacket receiveDp = new DatagramPacket(buf, buf.length);

      // 创建长度为100的数据接收包
      while (true) {
        Thread.sleep(50);
        _client.receive(receiveDp); // 套接字接收数据包
        String tmpStr = new String(buf, 0, receiveDp.getLength()).replace(" ", "");
        Strs += tmpStr;
        if (tmpStr.contains(SEND_CODE) && tmpStr.contains(",0")) {
          String strdev = tmpStr + "|" + receiveDp.getAddress();
          if (responses.indexOf(strdev) == -1) responses.add(strdev);
        }
      }
    } catch (Exception e) {
      if (listener != null) {
        listener.onError(e);
      }
    }
    if (listener != null) {
      listener.onFinish(responses);
    }
  }
  /**
   * {@collect.stats} {@description.open} Sends a datagram packet from this socket. The <code>
   * DatagramPacket</code> includes information indicating the data to be sent, its length, the IP
   * address of the remote host, and the port number on the remote host.
   *
   * <p>If there is a security manager, and the socket is not currently connected to a remote
   * address, this method first performs some security checks. First, if <code>
   * p.getAddress().isMulticastAddress()</code> is true, this method calls the security manager's
   * <code>checkMulticast</code> method with <code>p.getAddress()</code> as its argument. If the
   * evaluation of that expression is false, this method instead calls the security manager's <code>
   * checkConnect</code> method with arguments <code>p.getAddress().getHostAddress()</code> and
   * <code>p.getPort()</code>. Each call to a security manager method could result in a
   * SecurityException if the operation is not allowed. {@description.close}
   *
   * @param p the <code>DatagramPacket</code> to be sent.
   * @exception IOException if an I/O error occurs.
   * @exception SecurityException if a security manager exists and its <code>checkMulticast</code>
   *     or <code>checkConnect</code> method doesn't allow the send.
   * @exception PortUnreachableException may be thrown if the socket is connected to a currently
   *     unreachable destination. Note, there is no guarantee that the exception will be thrown.
   * @exception java.nio.channels.IllegalBlockingModeException if this socket has an associated
   *     channel, and the channel is in non-blocking mode.
   * @see java.net.DatagramPacket
   * @see SecurityManager#checkMulticast(InetAddress)
   * @see SecurityManager#checkConnect
   * @revised 1.4
   * @spec JSR-51
   */
  public void send(DatagramPacket p) throws IOException {
    InetAddress packetAddress = null;
    synchronized (p) {
      if (isClosed()) throw new SocketException("Socket is closed");
      checkAddress(p.getAddress(), "send");
      if (connectState == ST_NOT_CONNECTED) {
        // check the address is ok wiht the security manager on every send.
        SecurityManager security = System.getSecurityManager();

        // The reason you want to synchronize on datagram packet
        // is because you dont want an applet to change the address
        // while you are trying to send the packet for example
        // after the security check but before the send.
        if (security != null) {
          if (p.getAddress().isMulticastAddress()) {
            security.checkMulticast(p.getAddress());
          } else {
            security.checkConnect(p.getAddress().getHostAddress(), p.getPort());
          }
        }
      } else {
        // we're connected
        packetAddress = p.getAddress();
        if (packetAddress == null) {
          p.setAddress(connectedAddress);
          p.setPort(connectedPort);
        } else if ((!packetAddress.equals(connectedAddress)) || p.getPort() != connectedPort) {
          throw new IllegalArgumentException(
              "connected address " + "and packet address" + " differ");
        }
      }
      // Check whether the socket is bound
      if (!isBound()) bind(new InetSocketAddress(0));
      // call the  method to send
      getImpl().send(p);
    }
  }
Пример #19
0
  private InetMessagingAddress bind(
      DatagramSocket sock, InetAddress inetAddr, int port, int range) {
    InetMessagingAddress addr = null;
    boolean bound = false;

    if (range <= 0) range = 1;
    for (int i = 0; i < range; i++) {
      addr = new InetMessagingAddress(inetAddr, port + i);

      try {
        sock.bind(addr.getInetSocketAddress());

        port = port + i;
        bound = true;
        break;
      } catch (IOException e) {
        /*ignore*/
      }
    }

    if (!bound) addr = null;

    return addr;
  }
    protected Searcher(boolean _persistent, boolean _async) throws DeviceManagerException {

      try {
        int last_port = COConfigurationManager.getIntParameter("devices.tivo.net.tcp.port", 0);

        if (last_port > 0) {

          try {
            ServerSocket ss = new ServerSocket(last_port);

            ss.setReuseAddress(true);

            ss.close();

          } catch (Throwable e) {

            last_port = 0;
          }
        }

        twc = plugin_interface.getTracker().createWebContext(last_port, Tracker.PR_HTTP);

        tcp_port = twc.getURLs()[0].getPort();

        COConfigurationManager.setParameter("devices.tivo.net.tcp.port", tcp_port);

        twc.addPageGenerator(
            new TrackerWebPageGenerator() {
              public boolean generate(
                  TrackerWebPageRequest request, TrackerWebPageResponse response)
                  throws IOException {
                String id = (String) request.getHeaders().get("tsn");

                if (id == null) {

                  id = (String) request.getHeaders().get("tivo_tcd_id");
                }

                if (id != null && is_enabled) {

                  persistent = true;

                  DeviceTivo tivo =
                      foundTiVo(request.getClientAddress2().getAddress(), id, null, null);

                  return (tivo.generate(request, response));
                }

                return (false);
              }
            });

        control_socket = new DatagramSocket(null);

        control_socket.setReuseAddress(true);

        try {
          control_socket.setSoTimeout(60 * 1000);

        } catch (Throwable e) {
        }

        InetAddress bind = NetworkAdmin.getSingleton().getSingleHomedServiceBindAddress();

        control_socket.bind(new InetSocketAddress(bind, CONTROL_PORT));

        timer_event =
            SimpleTimer.addPeriodicEvent(
                "Tivo:Beacon",
                60 * 1000,
                new TimerEventPerformer() {
                  public void perform(TimerEvent event) {
                    if (!(manager_destroyed || search_destroyed)) {

                      sendBeacon();
                    }

                    // see if time to auto-shutdown searching

                    if (!persistent) {

                      synchronized (DeviceTivoManager.this) {
                        if (SystemTime.getMonotonousTime() - start >= LIFE_MILLIS) {

                          log("Terminating search, no devices found");

                          current_search = null;

                          destroy();
                        }
                      }
                    }
                  }
                });

        final AESemaphore start_sem = new AESemaphore("TiVo:CtrlListener");

        new AEThread2("TiVo:CtrlListener", true) {
          public void run() {
            start_sem.release();

            long successful_accepts = 0;
            long failed_accepts = 0;

            while (!(manager_destroyed || search_destroyed)) {

              try {
                byte[] buf = new byte[8192];

                DatagramPacket packet = new DatagramPacket(buf, buf.length);

                control_socket.receive(packet);

                successful_accepts++;

                failed_accepts = 0;

                if (receiveBeacon(packet.getAddress(), packet.getData(), packet.getLength())) {

                  persistent = true;
                }

              } catch (SocketTimeoutException e) {

              } catch (Throwable e) {

                if (control_socket != null && !search_destroyed && !manager_destroyed) {

                  failed_accepts++;

                  log("UDP receive on port " + CONTROL_PORT + " failed", e);
                }

                if ((failed_accepts > 100 && successful_accepts == 0) || failed_accepts > 1000) {

                  log("    too many failures, abandoning");

                  break;
                }
              }
            }
          }
        }.start();

        if (_async) {

          new DelayedEvent(
              "search:delay",
              5000,
              new AERunnable() {
                public void runSupport() {
                  sendBeacon();
                }
              });
        } else {

          start_sem.reserve(5000);

          sendBeacon();
        }

        log("Initiated device search");

      } catch (Throwable e) {

        log("Failed to initialise search", e);

        destroy();

        throw (new DeviceManagerException("Creation failed", e));
      }
    }
Пример #21
0
  /**
   * Receives a datagram packet from this socket. When this method returns, the <code>DatagramPacket
   * </code>'s buffer is filled with the data received. The datagram packet also contains the
   * sender's IP address, and the port number on the sender's machine.
   *
   * <p>This method blocks until a datagram is received. The <code>length</code> field of the
   * datagram packet object contains the length of the received message. If the message is longer
   * than the packet's length, the message is truncated.
   *
   * <p>If there is a security manager, a packet cannot be received if the security manager's <code>
   * checkAccept</code> method does not allow it.
   *
   * @param p the <code>DatagramPacket</code> into which to place the incoming data.
   * @exception IOException if an I/O error occurs.
   * @exception SocketTimeoutException if setSoTimeout was previously called and the timeout has
   *     expired.
   * @exception PortUnreachableException may be thrown if the socket is connected to a currently
   *     unreachable destination. Note, there is no guarantee that the exception will be thrown.
   * @exception java.nio.channels.IllegalBlockingModeException if this socket has an associated
   *     channel, and the channel is in non-blocking mode.
   * @see java.net.DatagramPacket
   * @see java.net.DatagramSocket
   * @revised 1.4
   * @spec JSR-51
   */
  public synchronized void receive(DatagramPacket p) throws IOException {
    synchronized (p) {
      if (!isBound()) bind(new InetSocketAddress(0));
      if (connectState == ST_NOT_CONNECTED) {
        // check the address is ok with the security manager before every recv.
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
          while (true) {
            String peekAd = null;
            int peekPort = 0;
            // peek at the packet to see who it is from.
            if (!oldImpl) {
              // We can use the new peekData() API
              DatagramPacket peekPacket = new DatagramPacket(new byte[1], 1);
              peekPort = getImpl().peekData(peekPacket);
              peekAd = peekPacket.getAddress().getHostAddress();
            } else {
              InetAddress adr = new InetAddress();
              peekPort = getImpl().peek(adr);
              peekAd = adr.getHostAddress();
            }
            try {
              security.checkAccept(peekAd, peekPort);
              // security check succeeded - so now break
              // and recv the packet.
              break;
            } catch (SecurityException se) {
              // Throw away the offending packet by consuming
              // it in a tmp buffer.
              DatagramPacket tmp = new DatagramPacket(new byte[1], 1);
              getImpl().receive(tmp);

              // silently discard the offending packet
              // and continue: unknown/malicious
              // entities on nets should not make
              // runtime throw security exception and
              // disrupt the applet by sending random
              // datagram packets.
              continue;
            }
          } // end of while
        }
      }
      if (connectState == ST_CONNECTED_NO_IMPL) {
        // We have to do the filtering the old fashioned way since
        // the native impl doesn't support connect or the connect
        // via the impl failed.
        boolean stop = false;
        while (!stop) {
          // peek at the packet to see who it is from.
          InetAddress peekAddress = new InetAddress();
          int peekPort = getImpl().peek(peekAddress);
          if ((!connectedAddress.equals(peekAddress)) || (connectedPort != peekPort)) {
            // throw the packet away and silently continue
            DatagramPacket tmp = new DatagramPacket(new byte[1], 1);
            getImpl().receive(tmp);
          } else {
            stop = true;
          }
        }
      }
      // If the security check succeeds, or the datagram is
      // connected then receive the packet
      getImpl().receive(p);
    }
  }
 public synchronized void bind(SocketAddress addr) throws SocketException {
   super.bind(addr);
   socketBindings.registerBinding(this);
 }
Пример #23
0
  void DatagramSocketTests() throws Exception {
    DatagramSocket s1 = new DatagramSocket(null);

    test("DatagramSocket should be created with SO_REUSEADDR disabled");
    check(!s1.getReuseAddress());

    test("DatagramSocket.setReuseAddress(true)");
    s1.setReuseAddress(true);
    check(s1.getReuseAddress());

    test("DatagramSocket.setReuseAddress(false)");
    s1.setReuseAddress(false);
    check(!s1.getReuseAddress());

    /* bind to any port */
    s1.bind(new InetSocketAddress(0));

    test("Binding datagram socket to port already in use should throw " + "a BindException");
    DatagramSocket s2 = new DatagramSocket(null);
    try {
      s2.bind(new InetSocketAddress(s1.getLocalPort()));
      failed();
    } catch (BindException e) {
      passed();
    }
    s2.close();
    s1.close();

    // bind with SO_REUSEADDR enabled

    s1 = new DatagramSocket(null);
    s1.setReuseAddress(true);
    s1.bind(new InetSocketAddress(0));

    test(
        "Bind 2 datagram sockets to the same port - second "
            + "bind doesn't have SO_REUSEADDR enabled");
    s2 = new DatagramSocket(null);
    try {
      s2.bind(new InetSocketAddress(s1.getLocalPort()));
      failed();
    } catch (BindException e) {
      passed();
    }
    s2.close();

    test("Bind 2 datagram sockets to the same port - both have " + "SO_REUSEADDR enabled");
    s2 = new DatagramSocket(null);
    s2.setReuseAddress(true);
    try {
      s2.bind(new InetSocketAddress(s1.getLocalPort()));
      passed();
    } catch (BindException e) {
      if (System.getProperty("sun.net.useExclusiveBind") != null) {
        // exclusive bind enabled - expected result
        passed();
      } else {
        failed();
      }
    }
    s2.close();

    s1.close();
  }