Example usage for java.net DatagramPacket getPort

List of usage examples for java.net DatagramPacket getPort

Introduction

In this page you can find the example usage for java.net DatagramPacket getPort.

Prototype

public synchronized int getPort() 

Source Link

Document

Returns the port number on the remote host to which this datagram is being sent or from which the datagram was received.

Usage

From source file:org.eclipse.smarthome.binding.ntp.server.SimpleNTPServer.java

private void handleRequest(DatagramPacket requestPacket) throws IOException {
    final long receivedTime = System.currentTimeMillis();
    NtpV3Packet responsePacket = new NtpV3Impl();
    responsePacket.setMode(NtpV3Packet.MODE_SERVER);
    responsePacket.setTransmitTime(TimeStamp.getNtpTime(receivedTime));
    DatagramPacket dataPacket = responsePacket.getDatagramPacket();
    dataPacket.setPort(requestPacket.getPort());
    dataPacket.setAddress(requestPacket.getAddress());
    socket.send(dataPacket);//from w  w  w  .j av  a  2 s  .  c o m
}

From source file:com.clearspring.metriccatcher.MetricCatcher.java

/**
 * Grab metric messages off the listening socket, creating and updating
 * them as needed.//ww  w .  j a  v a 2s . c  o m
 */
@Override
public void run() {
    // Arbitrary. One metric with a reasonable name is less than 200b
    // This (http://stackoverflow.com/q/3712151/17339) implies that 64 bit
    // leenuks will handle packets up to 24,258b, so let's assume we won't
    // get anything larger than that.  Note that this is a hard limit-you
    // can't accumulate from the socket so anything larger is truncated.
    byte[] data = new byte[24258];

    // Keep track of the last 1000 packets we've seen
    byte[] json = null;

    while (shutdown.get() == false) {
        DatagramPacket received = new DatagramPacket(data, data.length);
        try {
            // Pull in network data
            socket.receive(received);
            json = received.getData();
            if (logger.isDebugEnabled()) {
                logger.debug("Got packet from " + received.getAddress() + ":" + received.getPort());
                if (logger.isTraceEnabled()) {
                    String jsonString = new String(json);
                    logger.trace("JSON: " + jsonString);
                }
            }

            // Turn bytes of JSON into JSONMetric objects
            TypeReference<List<JSONMetric>> typeRef = new TypeReference<List<JSONMetric>>() {
            };
            List<JSONMetric> jsonMetrics = mapper.readValue(json, typeRef);

            // Parse all of the metrics in the message
            for (JSONMetric jsonMetric : jsonMetrics) {
                if (!metricCache.containsKey(jsonMetric.getName())) {
                    logger.info("Creating new " + jsonMetric.getType().name() + " metric for '"
                            + jsonMetric.getName() + "'");
                    Metric newMetric = createMetric(jsonMetric);
                    metricCache.put(jsonMetric.getName(), newMetric);
                }

                // Record the update
                logger.debug("Updating " + jsonMetric.getType() + " '" + jsonMetric.getName() + "' with <"
                        + jsonMetric.getValue() + ">");
                updateMetric(metricCache.get(jsonMetric.getName()), jsonMetric.getValue());
            }
        } catch (IOException e) {
            logger.warn("IO error: " + e);
            String jsonString = new String(json);
            logger.warn("JSON: " + jsonString);
        }
    }

    socket.close();
}

From source file:org.necsave.NecsaveTransport.java

private Message readMessage() throws Exception {
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    serverSocket.receive(receivePacket);

    ProtoInputStream pis = new ProtoInputStream(new ByteArrayInputStream(receiveData),
            ProtoDefinition.getInstance());

    Message msg = ProtoDefinition.getInstance().nextMessage(pis);

    if (msg instanceof PlatformInfo)
        process((PlatformInfo) msg, receivePacket.getAddress().getHostAddress(), receivePacket.getPort());

    NeptusLog.pub().debug("Received message of type '" + msg.getAbbrev() + "' from "
            + receivePacket.getAddress() + " - Platform " + platformNames.get(msg.getSrc()));

    return msg;//from   ww w.ja v a  2  s  .  c  o m
}

From source file:org.opennms.netmgt.syslogd.ConvertToEvent.java

/**
 * Constructs a new event encapsulation instance based upon the
 * information passed to the method. The passed datagram data is decoded
 * into a string using the <tt>US-ASCII</tt> character encoding.
 *
 * @param packet The datagram received from the remote agent.
 * @throws java.io.UnsupportedEncodingException
 *          Thrown if the data buffer cannot be decoded using the
 *          US-ASCII encoding./*w  ww. j  a va 2s .c om*/
 * @throws MessageDiscardedException 
 */
public ConvertToEvent(final DatagramPacket packet, final SyslogdConfig config)
        throws UnsupportedEncodingException, MessageDiscardedException {
    this(packet.getAddress(), packet.getPort(), new String(packet.getData(), 0, packet.getLength(), "US-ASCII"),
            config);
}

From source file:QuoteServerThread.java

 public void run() {
     if (socket == null)
         return;//from  w ww  .  j av  a 2  s. c o  m

     while (moreQuotes) {
         try {
             byte[] buf = new byte[256];
             DatagramPacket packet;
             InetAddress address;
             int port;
             String dString = null;

                 // receive request
             packet = new DatagramPacket(buf, 256);
             socket.receive(packet);
             address = packet.getAddress();
             port = packet.getPort();

                 // send response
             if (qfs == null)
                 dString = new Date().toString();
             else
                 dString = getNextQuote();
             buf = dString.getBytes();
             packet = new DatagramPacket(buf, buf.length, address, port);
             socket.send(packet);
         } catch (IOException e) {
             System.err.println("IOException:  " + e);
             moreQuotes = false;
             e.printStackTrace();
         }
     }
socket.close();
 }

From source file:org.avineas.fins.gw.Gateway.java

/**
 * The after properties set method of this gateway. The method initializes
 * a new thread that continuously reads from the UDP port for getting data
 * for local (or remote) nodes. This method <b>must</b> be called before
 * actual receiving of data can take place.
 *//*from   www.  j a  v  a 2 s .c om*/
@PostConstruct
public void init() throws SocketException {
    if (thread != null)
        return;
    if (channel == null)
        setPort(9600);

    // Initialize the nodes and handling of the packets.
    thread = new Thread() {
        @SuppressWarnings("synthetic-access")
        @Override
        public void run() {
            byte[] data = new byte[Frame.MAXFRAMESIZE];
            logger.info(Gateway.this + " started");
            for (;;) {
                try {
                    // Read a datagram from the network
                    DatagramPacket dpacket = new DatagramPacket(data, 0, data.length);
                    channel.receive(dpacket);

                    // Update the FINS node/gateway information
                    Destination dest = new Destination(dpacket.getAddress(), dpacket.getPort());
                    traceDatagram(dest + " -> " + channel.getLocalPort(), dpacket);
                    Frame packet = new Frame(data, dpacket.getLength());
                    Address from = packet.getSource();
                    setDestination(from.getNodeAsString(), dest);

                    // Handle the packet. It is either forwarded to
                    // a remote machine or locally handled. 
                    // Note that there is a possibility that gateways keep
                    // each other busy with sending data to each other. This
                    // cannot be prevented here.
                    Address to = packet.getDestination();
                    NodeUnit unit = units.get(to.toString());
                    if (unit != null) {
                        logger.info("received " + (packet.isReply() ? "reply" : "packet") + " frame from: "
                                + dest + ", for local unit: " + to + " from: " + packet.getSource());
                        Frame reply = unit.handleFrame(packet);
                        if (reply != null)
                            send(reply);
                    } else {
                        logger.info("frame for node " + to + " cannot be handled locally, trying forward");
                        send(packet);
                    }
                } catch (Exception exc) {
                    if (!runDown) {
                        synchronized (this) {
                            // Will normally only occur when the port is changed on the fly
                            logger.error("exception handling frame", exc);
                        }
                    }
                }
                // In case we were shut down, stop
                if (runDown)
                    break;
            }
            logger.info("FINS gateway shutdown complete");
        }
    };
    thread.start();
}

From source file:com.esri.geoevent.test.performance.ClockSync.java

@Override
public void run() {
    DatagramSocket socket = null;
    try {/* w w w  .jav  a2s. c  o m*/
        byte[] incomingBuffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(incomingBuffer, incomingBuffer.length);

        ByteBuffer bb = ByteBuffer.allocate(8);
        DatagramPacket outgoingPacket = new DatagramPacket(bb.array(), 0, 8, null, port);
        socket = new DatagramSocket(port);
        socket.setSoTimeout(100);
        while (isRunning.get()) {
            try {
                socket.receive(packet);
                long now = System.currentTimeMillis();
                bb.putLong(now);
                outgoingPacket.setAddress(packet.getAddress());
                outgoingPacket.setPort(packet.getPort());
                socket.send(outgoingPacket);
                bb.clear();
                //System.out.println("Sent the time " + now);
            } catch (SocketTimeoutException ex) {
                // Do nothing if nothing was sent.
            }
        }
    } catch (BindException e) {
        // port is in use - increment and try again
        port++;
        this.run();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(socket);
    }
}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.handlers.impl.PacketHandlerImpl.java

@Override
@Transactional//from w  ww  .ja  va 2s . c  om
public boolean processPacket(RelayServer relayServer, DatagramPacket packet) {
    try {
        this.txChecker.checkInTx("PacketHandler::processPacket");
    } catch (Throwable e) {
        e.printStackTrace();
    }

    long utcTimestamp = System.currentTimeMillis();
    boolean updated = false;

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("[" + utcTimestamp + "] Received " + packet.getLength() + " bytes from "
                + packet.getAddress().getHostAddress() + ":" + packet.getPort());
    }

    try {
        InetAddress srcIp = packet.getAddress();
        int srcPort = packet.getPort();

        /* get sender or create */
        Sender sender = this.senders.getSender(srcIp, srcPort);
        if (sender == null) {
            sender = new Sender(srcIp, Integer.valueOf(srcPort), relayServer);
        }

        /* make sure the sender is linked to this relayServer */
        sender.setRelayServer(relayServer);

        /* get packet data */
        byte[] packetData = packet.getData();
        int packetLength = packet.getLength();

        /* parse the uplink packet for messages */
        int messageOffset = 0;
        while (messageOffset < packetLength) {
            int messageType = UplinkMessage.getUplinkMessageType(packetData, messageOffset);
            int messageLength = UplinkMessage.getUplinkMessageHeaderLength()
                    + UplinkMessage.getUplinkMessageLength(packetData, messageOffset);

            if ((messageType != UplinkMessage.getUplinkMessageTypePosition())
                    && (messageType != UplinkMessage.getUplinkMessageTypeClusterLeader())) {
                this.logger.warn("Uplink message type " + messageType + " not supported: ignored");
            } else {
                byte[] messageData = Arrays.copyOfRange(packetData, messageOffset,
                        messageOffset + messageLength);
                DumpUtil.dumpUplinkMessage(this.logger, Level.DEBUG, messageData, srcIp, srcPort, messageType,
                        utcTimestamp, "  ");

                Object msg = null;
                boolean msgCausedUpdate = false;
                if (messageType == UplinkMessage.getUplinkMessageTypePosition()) {
                    msg = new PositionUpdate(messageData, messageLength);
                    msgCausedUpdate = this.positionUpdateHandler.handlePositionMessage(sender, utcTimestamp,
                            (PositionUpdate) msg);
                } else /* if (messageType == UplinkMessage.getUplinkMessageTypeClusterLeader()) */ {
                    msg = new ClusterLeader(messageData, messageLength);
                    msgCausedUpdate = this.clusterLeaderHandler.handleClusterLeaderMessage(sender, utcTimestamp,
                            (ClusterLeader) msg);
                }
                if (msgCausedUpdate && this.useFaker) {
                    this.faker.fakeit(sender, utcTimestamp, msg);
                }
                updated = msgCausedUpdate || updated;
            }

            messageOffset += messageLength;
        }

        return updated;
    } catch (Throwable e) {
        this.logger.error("error during packet handling", e);
        return updated;
    } finally {
        if (this.useFaker) {
            this.faker.setFirstFake(false);
        }
    }
}

From source file:MulticastClient.java

public void run() {

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

                // receive request
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);//from w w  w . j  av  a2s  . co  m

                // 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();
    }

From source file:gravity.android.discovery.DiscoveryServer.java

public void run() {
    Log.v("DISCOVERY_SERVER", "SERVER STARTED");

    DatagramSocket serverSocket = null;

    try {//from w ww . j a v a2s . com
        serverSocket = new DatagramSocket(port);
        byte[] receiveData;
        byte[] sendData;

        while (this.isInterrupted() == false) {
            receiveData = new byte[128];
            sendData = new byte[128];

            try {
                Log.v("DISCOVERY_SERVER", "LISTENING");
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                String sentence = new String(receivePacket.getData());

                if (sentence != null)
                    Log.v("DISCOVERY_SERVER",
                            "RECEIVED: " + sentence.substring(0, receivePacket.getLength()).trim());

                if (sentence != null && sentence.substring(0, receivePacket.getLength()).trim().equals(token)) {
                    Log.v("DISCOVERY_SERVER", "SEND '" + nome + "' to "
                            + receivePacket.getAddress().getHostAddress() + ":" + receivePacket.getPort());
                    JSONObject sendDataJson = new JSONObject();
                    sendDataJson.accumulate("name", nome);
                    sendDataJson.accumulate("port_to_share", port_to_share);

                    //sendData = (nome + "," + port_to_share).getBytes();
                    sendData = sendDataJson.toString().getBytes(); //Prakash: converts the data to json objects to avoid troubles

                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                            receivePacket.getAddress(), receivePacket.getPort());
                    serverSocket.send(sendPacket);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                Log.e("DISCOVERY_SERVER", ex.toString());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("DISCOVERY_SERVER", e.toString());
    } finally {
        try {
            if (serverSocket != null)
                serverSocket.close();
        } catch (Exception ex) {
        }
    }

}