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: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.ja  v a 2  s  .  co m*/
        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:MainClass.java

public static void main(String[] args) {

    try {//from w  w w .j  a va 2s.c  om
        String data = "data in UDP";
        byte[] buffer = data.getBytes();

        DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
                new InetSocketAddress("localhost", 5002));

        DatagramSocket socket = new DatagramSocket(5003);

        System.out.println("Sending a packet...");
        socket.send(packet);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:UDPReceive.java

public static void main(String args[]) {
    try {/*from  ww  w .ja v a2  s  . c  om*/
        if (args.length != 1)
            throw new IllegalArgumentException("Wrong number of args");

        // Get the port from the command line
        int port = Integer.parseInt(args[0]);

        // Create a socket to listen on the port.
        DatagramSocket dsocket = new DatagramSocket(port);

        // Create a buffer to read datagrams into. If anyone sends us a
        // packet containing more than will fit into 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);

        // Now loop forever, waiting to receive packets and printing them.
        for (;;) {
            // Wait to receive a datagram
            dsocket.receive(packet);

            // Decode the bytes of the packet to characters, using the
            // UTF-8 encoding, and then display those characters.
            String msg = new String(buffer, 0, packet.getLength(), "UTF-8");
            System.out.println(packet.getAddress().getHostName() + ": " + msg);

            // Reset the length of the packet before reusing it.
            // Prior to Java 1.1, we'd just create a new packet each time.
            packet.setLength(buffer.length);
        }
    } catch (Exception e) {
        System.err.println(e);
        System.err.println(usage);
    }
}

From source file:PacketReceiver.java

public static void main(String[] args) throws Exception {
    byte[] buffer = "data".getBytes();
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress("localhost", 5002));
    DatagramSocket socket = new DatagramSocket(5003);
    socket.send(packet);/*from  w ww  .  j ava 2s . c  o m*/
}

From source file:ChatClient.java

public static void main(String[] args) throws Exception {
        int PORT = 4000;
        byte[] buf = new byte[1000];
        DatagramPacket dgp = new DatagramPacket(buf, buf.length);
        DatagramSocket sk;/*  w  w  w  .  ja v  a  2  s . c  o  m*/

        sk = new DatagramSocket(PORT);
        System.out.println("Server started");
        while (true) {
            sk.receive(dgp);
            String rcvd = new String(dgp.getData(), 0, dgp.getLength()) + ", from address: " + dgp.getAddress()
                    + ", port: " + dgp.getPort();
            System.out.println(rcvd);

            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
            String outMessage = stdin.readLine();
            buf = ("Server say: " + outMessage).getBytes();
            DatagramPacket out = new DatagramPacket(buf, buf.length, dgp.getAddress(), dgp.getPort());
            sk.send(out);
        }
    }

From source file:Main.java

private static void BindPort() {
    Random random = new Random();
    port = random.nextInt(65535);/*w  w w. j a va  2 s .  c o m*/

    try {
        datagramSocket = new DatagramSocket(port);
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        BindPort();
    }
}

From source file:com.centeractive.ws.server.SimpleServerTest.java

public static boolean isPortAvailable(int port) {
    ServerSocket ss = null;//from   w  ww.j  a va 2 s  .c  o m
    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) {
            }
        }
    }
    return false;
}

From source file:com.kecso.socket.ServerSocketControl.java

@Override
public void run() {
    DatagramSocket sock = null;/*from   w w  w . j  a  va2  s . c  o m*/

    try {
        sock = new DatagramSocket(8888);
        sock.setSoTimeout(1000);

        byte[] buffer = new byte[65536];
        DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);

        while (!Thread.currentThread().isInterrupted()) {
            try {
                sock.receive(incoming);
                byte[] data = incoming.getData();
                this.udpMessage = SerializationUtils.deserialize(data);

                byte[] response = SerializationUtils.serialize(
                        this.output != null
                                ? new UdpResponse((float) output.getSpeed(), (float) output.getVerticalSpeed(),
                                        (float) output.getAltitude(), (float) output.getRpm())
                                : null);
                DatagramPacket dp = new DatagramPacket(response, response.length, incoming.getAddress(),
                        incoming.getPort());
                sock.send(dp);
            } catch (SocketTimeoutException e) {
            }
        }
    } catch (Exception e) {
        System.err.println("IOException " + e);
    } finally {
        if (sock != null) {
            sock.close();
        }

    }
}

From source file:com.wmfsystem.eurekaserver.broadcast.Server.java

public void run() {
    try {/*from   w  w w  .j ava 2 s .  c o m*/
        socket = new DatagramSocket(DEFAULT_PORT);
    } catch (Exception ex) {
        System.out.println("Problem creating socket on port: " + DEFAULT_PORT);
    }

    packet = new DatagramPacket(new byte[1], 1);

    while (true) {
        try {
            socket.receive(packet);
            System.out.println("Received from: " + packet.getAddress() + ":" + packet.getPort());
            byte[] outBuffer = new java.util.Date().toString().getBytes();
            packet.setData(outBuffer);
            packet.setLength(outBuffer.length);
            socket.setBroadcast(true);
            socket.send(packet);

            Set<InetAddress> localAddress = getLocalAddress();

            Set<String> ips = localAddress.stream().map(ad -> ad.getHostAddress()).collect(Collectors.toSet())
                    .stream().sorted().collect(Collectors.toSet());

            RestTemplate template = new RestTemplate();

            ips.forEach(ip -> {
                template.exchange("http://" + packet.getAddress().getHostAddress().concat(":8000?ip={ip}"),
                        HttpMethod.GET, HttpEntity.EMPTY, Void.class, ip.concat(":8000"));
                try {
                    template.exchange("http://" + packet.getAddress().getHostAddress().concat(":8000?ip={ip}"),
                            HttpMethod.GET, HttpEntity.EMPTY, Void.class, ip.concat(":8000"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            System.out.println("Message ----> " + packet.getAddress().getHostAddress());

        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }
}

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.ja v a  2 s  .  c om

    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;
}