Example usage for java.net DatagramPacket setPort

List of usage examples for java.net DatagramPacket setPort

Introduction

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

Prototype

public synchronized void setPort(int iport) 

Source Link

Document

Sets the port number on the remote host to which this datagram is being sent.

Usage

From source file:Main.java

public static void main(String args[]) {
    try {//from   w ww .  jav a  2s.  c o  m

        int port = 80;

        DatagramSocket ds = new DatagramSocket(port);

        byte buffer[] = new byte[BUFSIZE];

        while (true) {

            DatagramPacket dp = new DatagramPacket(buffer, buffer.length);

            dp.setPort(9090);

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

From source file:Main.java

public static void main(String[] args) throws Exception {
    int mcPort = 12345;
    String mcIPStr = "230.1.1.1";
    DatagramSocket udpSocket = new DatagramSocket();

    InetAddress mcIPAddress = InetAddress.getByName(mcIPStr);
    byte[] msg = "Hello".getBytes();
    DatagramPacket packet = new DatagramPacket(msg, msg.length);
    packet.setAddress(mcIPAddress);/*from  www .ja v  a  2 s  .c om*/
    packet.setPort(mcPort);
    udpSocket.send(packet);

    System.out.println("Sent a  multicast message.");
    System.out.println("Exiting application");
    udpSocket.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    byte[] ary = new byte[128];
    DatagramPacket pack = new DatagramPacket(ary, 128);

    // read//from  www  .ja  v a 2s .com
    DatagramSocket sock = new DatagramSocket(1111);
    sock.receive(pack);
    String word = new String(pack.getData());
    System.out.println("From: " + pack.getAddress() + " Port: " + pack.getPort());
    System.out.println(word);
    sock.close();
    // write
    sock = new DatagramSocket();
    pack.setAddress(InetAddress.getByName(args[1]));
    pack.setData(args[2].getBytes());
    pack.setPort(1111);
    sock.send(pack);
    sock.close();

}

From source file:UDP0.java

public static void main(String[] args) throws Exception {
    byte[] ary = new byte[128];
    DatagramPacket pack = new DatagramPacket(ary, 128);
    if (args[0].charAt(0) == 'r') {
        // read/*from ww w  .j  a v  a 2  s  .  c om*/
        DatagramSocket sock = new DatagramSocket(1111);
        sock.receive(pack);
        String word = new String(pack.getData());
        System.out.println("From: " + pack.getAddress() + " Port: " + pack.getPort());
        System.out.println(word);
        sock.close();
    } else { // write
        DatagramSocket sock = new DatagramSocket();
        pack.setAddress(InetAddress.getByName(args[1]));
        pack.setData(args[2].getBytes());
        pack.setPort(1111);
        sock.send(pack);
        sock.close();
    }
}

From source file:Main.java

public static DatagramPacket getPacket(String msg) throws UnknownHostException {
    int PACKET_MAX_LENGTH = 1024;
    byte[] msgBuffer = msg.getBytes();

    int length = msgBuffer.length;
    if (length > PACKET_MAX_LENGTH) {
        length = PACKET_MAX_LENGTH;//from   w  w  w. j  a  v  a2s  .  c o  m
    }
    DatagramPacket packet = new DatagramPacket(msgBuffer, length);
    InetAddress serverIPAddress = InetAddress.getByName("localhost");
    packet.setAddress(serverIPAddress);
    packet.setPort(15900);
    return packet;
}

From source file:SDRecord.java

private static long recordToSocket(DatagramPacket packet, DatagramSocket socket, InetAddress rhost,
        int destPort) {
    packet.setPort(destPort);
    packet.setAddress(rhost);/*  ww  w.  j a  v a2s.c  o m*/
    try {
        socket.send(packet);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(5);
    }
    return packet.getLength();
}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Returns the network address with which the task manager shall announce itself to the job manager. To determine
 * the address this method exchanges packets with the job manager.
 * /*from w  w w  . ja  v  a  2 s  .  c om*/
 * @param jobManagerAddress
 *        the address of the job manager
 * @return the address with which the task manager shall announce itself to the job manager
 * @throws DiscoveryException
 *         thrown if an error occurs during the packet exchange
 */
public static InetAddress getTaskManagerAddress(final InetAddress jobManagerAddress) throws DiscoveryException {

    final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER);
    final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT);

    InetAddress taskManagerAddress = null;
    DatagramSocket socket = null;

    try {

        socket = new DatagramSocket();
        LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT);
        socket.setSoTimeout(CLIENTSOCKETTIMEOUT);

        final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE],
                RESPONSE_PACKET_SIZE);

        for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) {

            final DatagramPacket addressRequest = createTaskManagerAddressRequestPacket(magicNumber);
            addressRequest.setAddress(jobManagerAddress);
            addressRequest.setPort(discoveryPort);

            LOG.debug("Sending Task Manager address request to " + addressRequest.getSocketAddress());
            socket.send(addressRequest);

            try {
                socket.receive(responsePacket);
            } catch (SocketTimeoutException ste) {
                LOG.warn("Timeout wainting for task manager address reply. Retrying...");
                continue;
            }

            if (!isPacketForUs(responsePacket, magicNumber)) {
                LOG.warn("Received packet which is not destined to this Nephele setup");
                continue;
            }

            final int packetTypeID = getPacketTypeID(responsePacket);
            if (packetTypeID != TM_ADDRESS_REPLY_ID) {
                LOG.warn("Received response of unknown type " + packetTypeID + ", discarding...");
                continue;
            }

            taskManagerAddress = extractInetAddress(responsePacket);
            break;
        }

    } catch (IOException ioe) {
        throw new DiscoveryException(StringUtils.stringifyException(ioe));
    } finally {
        if (socket != null) {
            socket.close();
        }
    }

    if (taskManagerAddress == null) {
        throw new DiscoveryException("Unable to obtain task manager address");
    }

    return taskManagerAddress;
}

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);/*w  w w  .  ja v a2s . c o  m*/
}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Attempts to retrieve the job managers address in the network through an
 * IP broadcast. This method should be called by the task manager.
 * //  w  w w  .jav  a2 s  . c  o m
 * @return the socket address of the job manager in the network
 * @throws DiscoveryException
 *         thrown if the job manager's socket address could not be
 *         discovered
 */
public static InetSocketAddress getJobManagerAddress() throws DiscoveryException {

    final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER);
    final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT);

    InetSocketAddress jobManagerAddress = null;
    DatagramSocket socket = null;

    try {

        final Set<InetAddress> targetAddresses = getBroadcastAddresses();

        if (targetAddresses.isEmpty()) {
            throw new DiscoveryException("Could not find any broadcast addresses available to this host");
        }

        socket = new DatagramSocket();

        LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT);
        socket.setSoTimeout(CLIENTSOCKETTIMEOUT);

        final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE],
                RESPONSE_PACKET_SIZE);

        for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) {

            final DatagramPacket lookupRequest = createJobManagerLookupRequestPacket(magicNumber);

            for (InetAddress broadcast : targetAddresses) {
                lookupRequest.setAddress(broadcast);
                lookupRequest.setPort(discoveryPort);
                LOG.debug("Sending discovery request to " + lookupRequest.getSocketAddress());
                socket.send(lookupRequest);
            }

            try {
                socket.receive(responsePacket);
            } catch (SocketTimeoutException ste) {
                LOG.debug("Timeout wainting for discovery reply. Retrying...");
                continue;
            }

            if (!isPacketForUs(responsePacket, magicNumber)) {
                LOG.debug("Received packet which is not destined to this Nephele setup");
                continue;
            }

            final int packetTypeID = getPacketTypeID(responsePacket);
            if (packetTypeID != JM_LOOKUP_REPLY_ID) {
                LOG.debug("Received unexpected packet type " + packetTypeID + ", discarding... ");
                continue;
            }

            final int ipcPort = extractIpcPort(responsePacket);

            // Replace port from discovery service with the actual RPC port
            // of the job manager
            if (USE_IPV6) {
                // TODO: No connection possible unless we remove the scope identifier
                if (responsePacket.getAddress() instanceof Inet6Address) {
                    try {
                        jobManagerAddress = new InetSocketAddress(
                                InetAddress.getByAddress(responsePacket.getAddress().getAddress()), ipcPort);
                    } catch (UnknownHostException e) {
                        throw new DiscoveryException(StringUtils.stringifyException(e));
                    }
                } else {
                    throw new DiscoveryException(responsePacket.getAddress() + " is not a valid IPv6 address");
                }
            } else {
                jobManagerAddress = new InetSocketAddress(responsePacket.getAddress(), ipcPort);
            }
            LOG.debug("Discovered job manager at " + jobManagerAddress);
            break;
        }

    } catch (IOException ioe) {
        throw new DiscoveryException(ioe.toString());
    } finally {
        if (socket != null) {
            socket.close();
        }
    }

    if (jobManagerAddress == null) {
        LOG.debug("Unable to discover Jobmanager via IP broadcast");
        throw new DiscoveryException("Unable to discover JobManager via IP broadcast!");
    }

    return jobManagerAddress;
}

From source file:poisondog.net.udp.DatagramMission.java

public DatagramResponse execute(DatagramParameter parameter) throws IOException {
    DatagramSocket socket = new DatagramSocket(null);
    socket.setReuseAddress(true);/*from  w w w. jav  a  2s .c  o m*/

    socket.setBroadcast(parameter.getBroadcast());
    if (parameter.getTimeout() > 0)
        socket.setSoTimeout(parameter.getTimeout());
    String data = IOUtils.toString(parameter.getInputStream());
    DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length());
    packet.setAddress(InetAddress.getByName(parameter.getHost()));
    packet.setPort(parameter.getPort());
    socket.send(packet);

    DatagramResponse response = new DatagramResponse(parameter.getResponseLength());
    DatagramPacket responsePacket = new DatagramPacket(response.getContent(), response.getContent().length);
    socket.receive(responsePacket);
    response.setAddress(responsePacket.getAddress().getHostAddress());
    response.setPacketLength(responsePacket.getLength());
    socket.close();
    return response;
}