Ejemplo n.º 1
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);
      }
    }
  }
Ejemplo n.º 2
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;
      }
    }
  /**
   * Activate this <tt>UDPTerminal</tt>.
   *
   * @throws Exception if there is a network failure.
   */
  public synchronized void activate() throws Exception {
    if (!isActive()) {
      if (Modbus.debug)
        CCLog.info(
            "UDPMasterTerminal::activate()::laddr=:" + m_LocalAddress + ":lport=" + m_LocalPort);

      if (m_Socket == null) {
        if (m_LocalAddress != null && m_LocalPort != -1) {
          m_Socket = new DatagramSocket(m_LocalPort, m_LocalAddress);
        } else {
          m_Socket = new DatagramSocket();
          m_LocalPort = m_Socket.getLocalPort();
          m_LocalAddress = m_Socket.getLocalAddress();
        }
      }
      if (Modbus.debug) CCLog.info("UDPMasterTerminal::haveSocket():" + m_Socket.toString());
      if (Modbus.debug)
        CCLog.info(
            "UDPMasterTerminal::laddr=:" + m_LocalAddress.toString() + ":lport=" + m_LocalPort);
      if (Modbus.debug)
        CCLog.info(
            "UDPMasterTerminal::raddr=:" + m_RemoteAddress.toString() + ":rport=" + m_RemotePort);

      m_Socket.setReceiveBufferSize(1024);
      m_Socket.setSendBufferSize(1024);

      m_ModbusTransport = new ModbusUDPTransport(this);
      m_Active = true;
    }
    if (Modbus.debug) CCLog.info("UDPMasterTerminal::activated");
  }
Ejemplo n.º 4
0
  /**
   * Activate this <tt>UDPTerminal</tt>.
   *
   * @throws Exception if there is a network failure.
   */
  public synchronized void activate() throws Exception {
    if (!isActive()) {
      if (Modbus.debug) System.out.println("UDPSlaveTerminal.activate()");
      if (m_Socket == null) {
        if (m_LocalAddress != null && m_LocalPort != -1) {
          m_Socket = new DatagramSocket(m_LocalPort, m_LocalAddress);
        } else {
          m_Socket = new DatagramSocket();
          m_LocalPort = m_Socket.getLocalPort();
          m_LocalAddress = m_Socket.getLocalAddress();
        }
      }
      if (Modbus.debug) System.out.println("UDPSlaveTerminal::haveSocket():" + m_Socket.toString());
      if (Modbus.debug)
        System.out.println(
            "UDPSlaveTerminal::addr=:" + m_LocalAddress.toString() + ":port=" + m_LocalPort);

      m_Socket.setReceiveBufferSize(1024);
      m_Socket.setSendBufferSize(1024);
      m_PacketReceiver = new PacketReceiver();
      m_Receiver = new Thread(m_PacketReceiver);
      m_Receiver.start();
      if (Modbus.debug) System.out.println("UDPSlaveTerminal::receiver started()");
      m_PacketSender = new PacketSender();
      m_Sender = new Thread(m_PacketSender);
      m_Sender.start();
      if (Modbus.debug) System.out.println("UDPSlaveTerminal::sender started()");
      m_ModbusTransport = new ModbusUDPTransport(this);
      if (Modbus.debug) System.out.println("UDPSlaveTerminal::transport created");
      m_Active = true;
    }
    if (Modbus.debug) System.out.println("UDPSlaveTerminal::activated");
  }
 @Override
 public void setReceiveBufferSize(int receiveBufferSize) {
   try {
     socket.setReceiveBufferSize(receiveBufferSize);
   } catch (SocketException e) {
     throw new ChannelException(e);
   }
 }
Ejemplo n.º 6
0
  /**
   * Konstruktor
   *
   * @param port UDP-Port, der lokal fuer das Datagramm-Socket verwendet werden soll
   * @param sendBufferSize Groesse des Sendepuffers in Byte
   * @param receiveBufferSize Groesse des Empfangspuffers in Byte
   */
  public UdpSocket(int port, int sendBufferSize, int receiveBufferSize) throws SocketException {
    socket = new DatagramSocket(port);
    try {
      socket.setReceiveBufferSize(receiveBufferSize);
      socket.setSendBufferSize(sendBufferSize);

      System.out.println(
          "Groesse des Empfangspuffers des Datagram-Sockets: "
              + socket.getReceiveBufferSize()
              + " Byte");
      System.out.println(
          "Groesse des Sendepuffers des Datagram-Sockets: " + socket.getSendBufferSize() + " Byte");
    } catch (SocketException e) {
      log.debug("Socketfehler: " + e);
    }
  }
 protected synchronized DatagramSocket getSocket() throws IOException {
   if (this.socket == null) {
     if (acknowledge) {
       if (logger.isDebugEnabled()) {
         logger.debug("Listening for acks on port: " + ackPort);
       }
       if (localAddress == null) {
         this.socket = new DatagramSocket(this.ackPort);
       } else {
         InetAddress whichNic = InetAddress.getByName(this.localAddress);
         this.socket = new DatagramSocket(this.ackPort, whichNic);
       }
       if (this.soReceiveBufferSize > 0) {
         socket.setReceiveBufferSize(this.soReceiveBufferSize);
       }
     } else {
       this.socket = new DatagramSocket();
     }
     setSocketAttributes(this.socket);
   }
   return this.socket;
 }
Ejemplo n.º 8
0
 public UdpSocketHandler(
     int listenPort,
     InetAddress bindto,
     Node node,
     long startupTime,
     String title,
     IOStatisticCollector collector)
     throws SocketException {
   this.node = node;
   this.collector = collector;
   this.title = title;
   _bindTo = bindto;
   // Keep the Updater code in, just commented out, for now
   // We may want to be able to do on-line updates.
   //		if (Updater.hasResource()) {
   //			_sock = (DatagramSocket) Updater.getResource();
   //		} else {
   this.listenPort = listenPort;
   _sock = new DatagramSocket(listenPort, bindto);
   int sz = _sock.getReceiveBufferSize();
   if (sz < 65536) {
     _sock.setReceiveBufferSize(65536);
   }
   try {
     // Exit reasonably quickly
     _sock.setReuseAddress(true);
   } catch (SocketException e) {
     throw new RuntimeException(e);
   }
   //		}
   // Only used for debugging, no need to seed from Yarrow
   dropRandom = node.fastWeakRandom;
   logMINOR = Logger.shouldLog(LogLevel.MINOR, this);
   logDEBUG = Logger.shouldLog(LogLevel.DEBUG, this);
   tracker = AddressTracker.create(node.lastBootID, node.runDir(), listenPort);
   tracker.startSend(startupTime);
 }
  /** The execution context. */
  @Override
  public void run() {
    // get the context
    m_context = Thread.currentThread();

    // Get a log instance
    ThreadCategory.setPrefix(m_logPrefix);
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    if (m_stop) {
      log.debug("Stop flag set before thread started, exiting");
      return;
    } else log.debug("Thread context started");

    // allocate a buffer
    final int length = 0xffff;
    final byte[] buffer = new byte[length];

    // set an SO timeout to make sure we don't block forever
    // if a socket is closed.
    try {
      log.debug("Setting socket timeout to " + SOCKET_TIMEOUT + "ms");
      m_dgSock.setSoTimeout(SOCKET_TIMEOUT);
    } catch (SocketException e) {
      log.warn("An I/O error occured while trying to set the socket timeout", e);
    }

    // Increase the receive buffer for the socket
    try {
      log.debug("Setting receive buffer size to " + length);
      m_dgSock.setReceiveBufferSize(length);
    } catch (SocketException e) {
      log.info("Failed to set the receive buffer to " + length, e);
    }
    // set to avoid numerous tracing message
    boolean ioInterrupted = false;
    // now start processing incoming requests
    while (!m_stop) {
      if (m_context.isInterrupted()) {
        log.debug("Thread context interrupted");
        break;
      }

      try {
        if (!ioInterrupted) {
          log.debug("Waiting on a datagram to arrive");
        }

        DatagramPacket pkt = new DatagramPacket(buffer, length);
        m_dgSock.receive(pkt);

        // SyslogConnection *Must* copy packet data and InetAddress as DatagramPacket is a mutable
        // type
        WaterfallExecutor.waterfall(
            m_executors,
            new SyslogConnection(
                pkt,
                m_matchPattern,
                m_hostGroup,
                m_messageGroup,
                m_UeiList,
                m_HideMessages,
                m_discardUei));
        ioInterrupted = false; // reset the flag
      } catch (SocketTimeoutException e) {
        ioInterrupted = true;
        continue;
      } catch (InterruptedIOException e) {
        ioInterrupted = true;
        continue;
      } catch (ExecutionException e) {
        log.error("Task execution failed in " + this.getClass().getSimpleName(), e);
        break;
      } catch (InterruptedException e) {
        log.error("Task interrupted in " + this.getClass().getSimpleName(), e);
        break;
      } catch (IOException e) {
        log.error("An I/O exception occured on the datagram receipt port, exiting", e);
        break;
      }
    } // end while status OK

    log.debug("Thread context exiting");
  }
Ejemplo n.º 10
0
 public void run() {
   DatagramSocket socketCopy = socket;
   if (socketCopy != null) {
     try {
       socketCopy.setSoTimeout(getSocketTimeout());
       if (receiveBufferSize > 0) {
         socketCopy.setReceiveBufferSize(Math.max(receiveBufferSize, maxInboundMessageSize));
       }
       if (logger.isDebugEnabled()) {
         logger.debug(
             "UDP receive buffer size for socket "
                 + getAddress()
                 + " is set to: "
                 + socketCopy.getReceiveBufferSize());
       }
     } catch (SocketException ex) {
       logger.error(ex);
       setSocketTimeout(0);
     }
   }
   while (!stop) {
     DatagramPacket packet =
         new DatagramPacket(buf, buf.length, udpAddress.getInetAddress(), udpAddress.getPort());
     try {
       socketCopy = socket;
       try {
         if (socketCopy == null) {
           stop = true;
           continue;
         }
         socketCopy.receive(packet);
       } catch (InterruptedIOException iiox) {
         if (iiox.bytesTransferred <= 0) {
           continue;
         }
       }
       if (logger.isDebugEnabled()) {
         logger.debug(
             "Received message from "
                 + packet.getAddress()
                 + "/"
                 + packet.getPort()
                 + " with length "
                 + packet.getLength()
                 + ": "
                 + new OctetString(packet.getData(), 0, packet.getLength()).toHexString());
       }
       ByteBuffer bis;
       // If messages are processed asynchronously (i.e. multi-threaded)
       // then we have to copy the buffer's content here!
       if (isAsyncMsgProcessingSupported()) {
         byte[] bytes = new byte[packet.getLength()];
         System.arraycopy(packet.getData(), 0, bytes, 0, bytes.length);
         bis = ByteBuffer.wrap(bytes);
       } else {
         bis = ByteBuffer.wrap(packet.getData());
       }
       TransportStateReference stateReference =
           new TransportStateReference(
               DefaultUdpTransportMapping.this,
               udpAddress,
               null,
               SecurityLevel.undefined,
               SecurityLevel.undefined,
               false,
               socketCopy);
       fireProcessMessage(
           new UdpAddress(packet.getAddress(), packet.getPort()), bis, stateReference);
     } catch (SocketTimeoutException stex) {
       // ignore
     } catch (PortUnreachableException purex) {
       synchronized (DefaultUdpTransportMapping.this) {
         listener = null;
       }
       logger.error(purex);
       if (logger.isDebugEnabled()) {
         purex.printStackTrace();
       }
       if (SNMP4JSettings.isFowardRuntimeExceptions()) {
         throw new RuntimeException(purex);
       }
       break;
     } catch (SocketException soex) {
       if (!stop) {
         logger.error(
             "Socket for transport mapping " + toString() + " error: " + soex.getMessage(),
             soex);
       }
       if (SNMP4JSettings.isFowardRuntimeExceptions()) {
         stop = true;
         throw new RuntimeException(soex);
       }
     } catch (IOException iox) {
       logger.warn(iox);
       if (logger.isDebugEnabled()) {
         iox.printStackTrace();
       }
       if (SNMP4JSettings.isFowardRuntimeExceptions()) {
         throw new RuntimeException(iox);
       }
     }
   }
   synchronized (DefaultUdpTransportMapping.this) {
     listener = null;
     stop = true;
     DatagramSocket closingSocket = socket;
     if ((closingSocket != null) && (!closingSocket.isClosed())) {
       closingSocket.close();
     }
   }
   if (logger.isDebugEnabled()) {
     logger.debug("Worker task stopped:" + getClass().getName());
   }
 }
Ejemplo n.º 11
0
  public static void main(String[] args) throws IOException {

    long start = System.currentTimeMillis();
    long used = 0;
    long total = 10000000;
    long step = 2000;

    int port = 8080;

    // Create a socket to listen on the port.
    DatagramSocket dsocket = new DatagramSocket(port, InetAddress.getByName("192.168.1.107"));
    // Create a buffer to read datagrams into. If a
    // packet is larger than this buffer, the
    // excess will simply be discarded!
    byte[] buffer = new byte[2048];
    // Create a packet to receive data into the buffer
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
    // String[] s = new String[(int)total];

    // Now loop forever, waiting to receive packets and printing them.
    dsocket.setSoTimeout(1000);
    // actually useless
    dsocket.setReceiveBufferSize(3145728);
    System.out.println("dsocket.getReceiveBufferSize():" + dsocket.getReceiveBufferSize());

    while (used < 30000) {
      // Wait to receive a datagram
      try {
        dsocket.receive(packet);
      } catch (Exception e) {
        // continue ;
        used = System.currentTimeMillis() - start;
        continue;
      }

      // Convert the contents to a string, and display them
      String msg = new String(buffer, 0, packet.getLength());
      // s[cnt] = msg;
      // Reset the length of the packet before reusing it.
      packet.setLength(buffer.length);

      cnt++;
      if (cnt % (step) == 0) {
        used = System.currentTimeMillis() - start;
        System.out.println(
            "recive package:" + cnt + " through-put:" + ((double) cnt / (double) used) * 1000);
        System.out.println(msg);
      }

      if (cnt == total) break;
    }

    used = System.currentTimeMillis() - start;
    System.out.print(
        "used time: "
            + used
            + "ms total: "
            + cnt
            + " pkgs through-put:"
            + ((double) cnt / (double) used) * 1000
            + " req/s lost-package:"
            + (total - cnt));
  }