Example usage for java.net DatagramSocket DatagramSocket

List of usage examples for java.net DatagramSocket DatagramSocket

Introduction

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

Prototype

public DatagramSocket(int port) throws SocketException 

Source Link

Document

Constructs a datagram socket and binds it to the specified port on the local host machine.

Usage

From source file:org.springframework.integration.ip.udp.UdpChannelAdapterTests.java

@SuppressWarnings("unchecked")
@Test//w w  w .  ja v  a2  s  .  c om
public void testUnicastReceiver() throws Exception {
    QueueChannel channel = new QueueChannel(2);
    int port = SocketUtils.findAvailableUdpSocket();
    UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port);
    adapter.setOutputChannel(channel);
    //      SocketUtils.setLocalNicIfPossible(adapter);
    adapter.start();
    SocketTestUtils.waitListening(adapter);

    Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build();
    DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
    DatagramPacket packet = mapper.fromMessage(message);
    packet.setSocketAddress(new InetSocketAddress("localhost", port));
    new DatagramSocket(SocketUtils.findAvailableUdpSocket()).send(packet);
    Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000);
    assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload()));
}

From source file:com.lfv.yada.net.server.ServerNetworkManager.java

public ServerNetworkManager(int port, ServerBundle bundle, ServerTranslator translator) throws SocketException {
    // Create a logger for this class
    log = LogFactory.getLog(getClass());
    log.debug("Creating server at port " + port);

    this.bundle = bundle;
    this.translator = translator;

    // The the socket to be used for sending and receiving packets
    DatagramSocket socket = new DatagramSocket(port);

    // Create a receiver and a sender
    receiver = new ServerPacketReceiver(socket, bundle);
    sender = new ServerPacketSender(socket);

    // Create a transaction mananger
    transactionManager = new TransactionManager(sender);
    receiver.setControlPacketDispatcher(transactionManager);
    receiver.setSendPacketDispatcher(sender);

    // Create a timer for handling terminal timeout
    timer = new Timer("Snetworkmanager", true);

    // Initialize packet pool
    PacketPool.getPool();/*from  w w  w.j a  va  2 s. co  m*/

    // Setup request handlers
    transactionManager.setRequestHandler(Packet.PING, new PingRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.UPDATE, new UpdateRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.INITIATE, new InitiateRequestPacketHandler());
}

From source file:jlg.jade.test.asterix.cat062.Cat062LargeSampleTest.java

@Test
@Ignore("Can only be executed if an Asterix sender is feeding the decoder")
public void when_upd_unicast_is_used_as_input_and_datagram_is_large_should_decode_cat062_messages_from_larger_sample()
        throws IOException {
    //arrange/*w ww  .  ja  v a  2  s .c  o  m*/
    final int PORT = 3001;
    final int MAX_PACKET_SIZE = 65507;
    final int TIMEOUT = 20000;

    //act
    AsterixDecoder decoder = new AsterixDecoder(62);
    byte[] networkBuffer = new byte[MAX_PACKET_SIZE];
    int receivedDatagrams = 0;
    int receivedBytes = 0;
    try (DatagramSocket client = new DatagramSocket(PORT)) {
        client.setSoTimeout(TIMEOUT);
        DatagramPacket packet = new DatagramPacket(networkBuffer, networkBuffer.length);
        while (true) {
            client.receive(packet);
            List<AsterixDataBlock> dataBlocks = decoder.decode(networkBuffer, 0, packet.getLength());
            for (AsterixDataBlock dataBlock : dataBlocks) {
                for (AsterixRecord rec : dataBlock.getRecords()) {
                    System.out.println("Decoded new record");
                }
            }

            //accumulate and print info
            receivedDatagrams++;
            receivedBytes += packet.getLength();
            if (receivedDatagrams % 100 == 0) {
                System.out
                        .println("Processed " + receivedDatagrams + " datagrams (" + receivedBytes + ") bytes");
            }
        }
    }

    //assert
    //int expectedDatagrams = 34957;
    //int expectedBytes = 2306154;
    //assertEquals(expectedDatagrams, receivedDatagrams);
    //assertEquals(expectedBytes, receivedBytes);
}

From source file:udpserver.UDPui.java

private void tempReceiveUDP() {
    background = new Runnable() {
        public void run() {
            try {
                serverSocket = new DatagramSocket(9876);
            } catch (SocketException ex) {
                Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
            }//from  w  w  w  . j  a  v  a2s.  co m
            //                while (true) {
            //                    byte[] receiveData = new byte[1024];
            //                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            //                    if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) {
            //                        int count = 1;
            while (true) {
                try {
                    byte[] receiveData = new byte[total_byte];
                    byte[] sendData = new byte[32];
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                    serverSocket.receive(receivePacket);
                    String message = new String(receivePacket.getData(), receivePacket.getOffset(),
                            receivePacket.getLength());
                    //                                String word = serverSocket.getInetAddress().toString();
                    //                                Integer count = counting.get(word);
                    //                                if (count == null) {
                    //                                    counting.put(word, 1);
                    //                                }
                    //                                else {
                    //                                    counting.put(word, count + 1);
                    //                                }

                    boolean looprun = true;
                    String word = receivePacket.getAddress().getHostAddress();
                    System.out.println(word);
                    //                        System.out.println(message);
                    while (looprun) {
                        if (message.contains("&")) {
                            message = message.substring(message.indexOf("&") + 1);
                            Integer count = counting.get(word);
                            if (count == null) {
                                counting.put(word, 2);
                            } else {
                                counting.put(word, count + 1);
                            }
                            //                                System.out.println(count + ":" + message);
                        } else {
                            looprun = false;
                        }
                    }

                    if (message.equals("end")) {
                        valuePane.setCaretPosition(valuePane.getDocument().getLength());
                        //send back to mobile
                        InetAddress IPAddress = receivePacket.getAddress();
                        int port = receivePacket.getPort();
                        String capitalizedSentence = counting.get(word) + "";
                        sendData = capitalizedSentence.getBytes();
                        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
                                port);
                        serverSocket.send(sendPacket);
                        //end send back to mobile
                        //                                    count = 1;
                        //                                    break;
                        counting.remove(word);
                    } else if (available) {

                        //                                    series.add(count, Double.parseDouble(message));
                        //                                    valuePane.setText(valuePane.getText().toString() + count + ":" + message + "\n");
                        //                                    valuePane.setCaretPosition(valuePane.getDocument().getLength());
                        //                                    count++;
                    }
                } catch (IOException ex) {
                    Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            //                    }
            //                }
        }
    };
    backgroundProcess = new Thread(background);
}

From source file:examples.ntp.SimpleNTPServer.java

/**
 * Connect to server socket and listen for client connections.
 *
 * @throws IOException if an I/O error occurs when creating the socket.
 *//*from w  w  w  .  j  av  a  2  s. c  o  m*/
public void connect() throws IOException {
    if (socket == null) {
        socket = new DatagramSocket(port);
        // port = 0 is bound to available free port
        if (port == 0) {
            port = socket.getLocalPort();
        }
        System.out.println("Running NTP service on port " + port + "/UDP");
    }
}

From source file:org.necsave.NecsaveTransport.java

public NecsaveTransport(ConsoleLayout console) throws Exception {
    this.console = console;
    boolean bound = false;
    for (int port = broadcastPort; port < broadcastPort + 3; port++) {
        try {/* w  w  w  . j  a  v a2s  .  com*/
            serverSocket = new DatagramSocket(null);
            serverSocket.setReuseAddress(true);
            serverSocket.setBroadcast(true);
            serverSocket.bind(new InetSocketAddress(port));
            NeptusLog.pub().info(I18n.textf("Bound to port %d", port));
            bound = true;
            break;
        } catch (Exception e) {
            e.printStackTrace();
            NeptusLog.pub().error(I18n.textf("Unable to bind to port %port: %error", port, e.getMessage()));
        }
    }
    if (!bound)
        throw new RuntimeException("Unable to bind to any broadcast port.");

    receiverThread.setDaemon(true);
    receiverThread.start();
}

From source file:yatftps.Yatftps.java

/**
 * main method listen to 69 port UDP.//from www. jav a 2 s  . c om
 * After receiving connection creates new thread for processing request.
 * @param args the command line arguments
 */
//public static void main(String[] args) {
@Override
public void init(DaemonContext daemonContext) throws DaemonInitException, Exception {

    String[] args = daemonContext.getArguments();
    LogWriter.readConfig();
    log = LogWriter.getLogger();
    Config cfg;

    /*
    * Accordingly RFC 1350 the data field is from zero to 512 bytes long. https://tools.ietf.org/html/rfc1350
    * Respectively  (Data Field) + (Block Field) + (Opcode Field) = 512 + 2 + 2 = 516 bytes
    */
    datagramLength = 516;
    /*
    * Reading config file and getting application settings
    */
    cfg = Config.getConfig();
    /*
    * Checking for start arguments
    */
    if (args.length >= 1) {
        for (String s : args) {
            switch (s) {
            case "--debug":
                LogWriter.setDebug(true);
                break;
            case "--check-config":
                Config.checkConfig();
                System.exit(0);
            }
        }
    }

    yatftpsThread = new Thread() {

        @Override
        public synchronized void start() {
            Yatftps.this.stopped = false;
            super.start();
        }

        @Override
        public void run() {
            while (!stopped) {

                log.info("Server started");

                // trying to listen port 69
                try (DatagramSocket socket = new DatagramSocket(69)) {

                    // receive first packet from client
                    DatagramPacket datapacket = new DatagramPacket(new byte[datagramLength], 0, datagramLength);
                    socket.receive(datapacket);

                    // create new thread for handling TFTP request
                    TftpHandler tftphandler = new TftpHandler(socket, datapacket);
                    Thread thread = new Thread(tftphandler);

                    thread.setDaemon(true);
                    thread.start();

                } catch (SocketException e) {
                    log.severe(
                            "SocketException: socket could not be opened, or the socket could not bind to the specified local port.  "
                                    + e);
                    log.info("Exiting");
                    System.exit(1);
                } catch (SecurityException e) {
                    log.severe(
                            "SecurityException: security manager exists and its checkListen method doesn't allow the operation "
                                    + e);
                    log.info("Exiting");
                    System.exit(1);
                } catch (IOException e) {
                    log.info("I/O error occurs" + e);
                }
            }
        }
    };
}

From source file:org.rifidi.emulator.io.comm.ip.udp.UDPCommunication.java

/**
 * A constructor for a UDPCommunication. Takes in the local IP/port to bind
 * to and and the remote IP/port to send data to.
 * //ww w .  java 2  s .  co m
 * @param initialPowerState
 *            The initial power state.
 * @param initialConnectionState
 *            The initial connection state.
 * @param localIP
 *            The local IP to bind to.
 * @param localPort
 *            The local port to bind to.
 * @param remoteIP =
 *            new DatagramSocket() The remote IP to send data to.
 * @param remotePort
 *            The remote port to send data to.
 * @param protocol
 *            The protocol that this session will be using.
 */
public UDPCommunication(Protocol prot, ControlSignal<Boolean> powerControlSignal,
        ControlSignal<Boolean> connectionControlSignal, String localIP, int localPort, boolean outputOnly)
        throws CommunicationException {

    /* call the super constructor for ip communication and set vars */
    super(UDPOffCommunicationPowerState.getInstance(),
            UDPConnectionlessCommunicationConnectionState.getInstance(), prot, powerControlSignal,
            connectionControlSignal, localIP, localPort, null, 0);

    /* Validate that the ip parameters passed in are not null */
    if (localIP == null || !GeneralFormattingUtility.isValidIPPort(localPort)) {
        throw new CommunicationException("Invalid ip Parameters");
    }

    /* This variable is used to indicate outgoing UPD packets only */
    this.outputOnly = outputOnly;

    try {
        newSock = new DatagramSocket(null);
    } catch (SocketException e) {
        logger.warn(e.getMessage());

    }
    this.prot = prot;
    System.out.println("UDP communication created successfuly");
}

From source file:net.tanesha.tftpd.core.Server.java

public void afterPropertiesSet() throws Exception {

    // initialize port.
    try {/*  ww w.jav  a  2s  . com*/
        // bind to the socket
        InetSocketAddress saddr = new InetSocketAddress(bindhost, port);

        // create the socket to listen on.
        serverSocket = new DatagramSocket(saddr);

    } catch (SocketException e) {
        throw new RuntimeException("Startup failed: Couldn't create socket on port '" + port + "'", e);
    }

    // start retransmit timer.
    timeoutHandler = new TimeoutMonitor(this);
    timeoutHandlerThread = new Thread(timeoutHandler);
    timeoutHandlerThread.start();

    serverHandlerThread = new Thread(new ServerRunner());
    serverHandlerThread.start();
}

From source file:org.apache.hama.util.BSPNetUtils.java

/**
 * Checks to see if a specific port is available.
 * //from   w ww.  j a va  2  s .c  o m
 * @param port the port to check for availability
 */
public static boolean available(int port) {
    if (port < 1000 || port > MAX_PORT_NUMBER) {
        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) {
    } finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }

    return false;
}