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.starnub.starnubserver.servers.starbound.UDPProxyServer.java

public void run() {
    InetAddress IPAddress;/*w w w .  j ava  2  s  .  c  o  m*/
    DatagramSocket ds;
    try {
        ds = new DatagramSocket(starnubPort);
        IPAddress = InetAddress.getByName(starboundAddress);
    } catch (SocketException | UnknownHostException e1) {
        StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e1));
        e1.printStackTrace();
        return;
    }

    byte[] request = new byte[1024];
    byte[] reply = new byte[4096];

    while (!stopping) {
        try {
            DatagramPacket from_client = new DatagramPacket(request, request.length);
            ds.receive(from_client);

            byte[] real_request = new byte[from_client.getLength()];
            System.arraycopy(request, 0, real_request, 0, from_client.getLength());

            DatagramPacket sendPacket = new DatagramPacket(real_request, real_request.length, IPAddress,
                    starboundPort);
            ds.send(sendPacket);

            DatagramPacket from_server = new DatagramPacket(reply, reply.length);
            ds.receive(from_server);
            byte[] real_reply = new byte[from_server.getLength()];
            System.arraycopy(reply, 0, real_reply, 0, from_server.getLength());

            InetAddress address = from_client.getAddress();
            int port = from_client.getPort();
            DatagramPacket to_client = new DatagramPacket(real_reply, real_reply.length, address, port);
            ds.send(to_client);
        } catch (Exception e) {
            StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e));
            return;
        }
    }
}

From source file:GossipP2PServer.java

/**
 * Setup current server as a concurrent server.
 * @param port Port that server is listening on.
 *///from   w w  w .  j  a  v  a2  s . c  om
static void runConcurrentServer(int port) {
    Socket sock;

    try {
        ServerSocket serverSocket = new ServerSocket(port);
        DatagramSocket dgSocket = new DatagramSocket(port);

        for (;;) {

            new ConcurrentUDPServerThread(dgSocket).start();
            sock = serverSocket.accept();
            new ConcurrentTCPServerThread(sock).start();

        }
    } catch (Exception e) {

    }
}

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

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

    DatagramSocket serverSocket = null;

    try {//from www . j  ava 2 s.c  om
        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) {
        }
    }

}

From source file:org.squidy.manager.protocol.udp.UDPServer.java

public UDPServer(int port) {
    try {/*from   ww w .  j ava2 s  .  c  o m*/
        socket = new DatagramSocket(port);
        start();
        LOG.info("UDP Server started on port " + port);
    } catch (IOException e) {
        LOG.error("Couldn't start udp server on port " + port);
    }

}

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

/**
 * This method opens a new socket and receives requests calling handleRequest() for each one.
 *//*  w w  w  .ja  v a 2s . c o m*/
public void startServer() {
    isRunning = true;

    new Thread() {
        @Override
        public void run() {
            try {
                socket = new DatagramSocket(port);
            } catch (SocketException e) {
                logger.error("Occured an error {}. Couldn't open a socket on this port:", port, e);
            }
            while (isRunning) {
                try {
                    socket.receive(request);
                    handleRequest(request);
                } catch (IOException e) {
                    logger.error("There was an error {} while processing the request!", request, e);
                }
            }
        }
    }.start();
}

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

@Test
public void verifySend() throws Exception {
    final int testPort = SocketUtils.findAvailableUdpSocket();
    byte[] buffer = new byte[8];
    final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
    final CountDownLatch latch = new CountDownLatch(1);
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket(testPort);
                socket.receive(receivedPacket);
                latch.countDown();// w  w  w .  j ava  2  s. c o m
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    Thread.sleep(1000);
    UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort);
    String payload = "foo";
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch.await(3000, TimeUnit.MILLISECONDS));
    byte[] src = receivedPacket.getData();
    int length = receivedPacket.getLength();
    int offset = receivedPacket.getOffset();
    byte[] dest = new byte[length];
    System.arraycopy(src, offset, dest, 0, length);
    assertEquals(payload, new String(dest));
    handler.shutDown();
}

From source file:com.buaa.cfs.nfs3.PrivilegedNfsGatewayStarter.java

@Override
public void init(DaemonContext context) throws Exception {
    System.err.println("Initializing privileged NFS client socket...");
    NfsConfiguration conf = new NfsConfiguration();
    int clientPort = conf.getInt(NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY,
            NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_DEFAULT);
    if (clientPort < 1 || clientPort > 1023) {
        throw new RuntimeException("Must start privileged NFS server with '"
                + NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY + "' configured to a " + "privileged port.");
    }/*from  w w  w  .  ja v a 2 s . c o  m*/
    registrationSocket = new DatagramSocket(new InetSocketAddress("localhost", clientPort));
    registrationSocket.setReuseAddress(true);
    args = context.getArguments();
}

From source file:com.clustercontrol.winsyslog.SyslogReceiver.java

public synchronized void start() throws SocketException, UnknownHostException, IOException {

    if (tcpEnable) {
        tcpSocket = new ServerSocket(listenPort);
        tcpExecutor = createExecutorService("TcpReceiver");
        tcpExecutor.submit(new TcpReceiverTask(tcpSocket));
    }//from w w w  .j a va  2s  .c o  m

    if (udpEnable) {
        udpSocket = new DatagramSocket(listenPort);
        udpExecutor = createExecutorService("UdpReceiver");
        udpExecutor.submit(new UdpReceiverTask(udpSocket));
    }

    if (!tcpEnable && !udpEnable) {
        log.warn("Both TCP and UDP are disabled.");
    }
}

From source file:com.clustercontrol.poller.impl.UdpTransportMappingImpl.java

/**
 * Creates a UDP transport with an arbitrary local port on all local
 * interfaces./*from w  w w.  j av  a 2s.c  om*/
 *
 * @throws IOException
 *             if socket binding fails.
 */
public UdpTransportMappingImpl() throws IOException {
    super(new UdpAddress("0.0.0.0/0"));
    socket = new DatagramSocket(udpAddress.getPort());
}

From source file:us.nineworlds.serenity.core.services.GDMService.java

@Override
protected void onHandleIntent(Intent intent) {
    try {/*from   www .j  a  v  a2  s  . c  o m*/
        DatagramSocket socket = new DatagramSocket(32414);
        socket.setBroadcast(true);
        String data = "M-SEARCH * HTTP/1.1\r\n\r\n";
        DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), useMultiCastAddress(),
                32414);
        //         DatagramPacket packet = new DatagramPacket(data.getBytes(),
        //               data.length(), getBroadcastAddress(), 32414);

        socket.send(packet);
        Log.d("GDMService", "Search Packet Broadcasted");

        byte[] buf = new byte[256];
        packet = new DatagramPacket(buf, buf.length);
        socket.setSoTimeout(2000);
        boolean listening = true;
        while (listening) {
            try {
                socket.receive(packet);
                String packetData = new String(packet.getData());
                if (packetData.contains("HTTP/1.0 200 OK")) {
                    Log.d("GDMService", "PMS Packet Received");
                    // Broadcast Received Packet
                    Intent packetBroadcast = new Intent(GDMService.MSG_RECEIVED);
                    packetBroadcast.putExtra("data", packetData);
                    packetBroadcast.putExtra("ipaddress", packet.getAddress().toString());
                    LocalBroadcastManager.getInstance(this).sendBroadcast(packetBroadcast);
                }
            } catch (SocketTimeoutException e) {
                Log.d("GDMService", "Socket Timeout");
                socket.close();
                listening = false;
                Intent socketBroadcast = new Intent(GDMService.SOCKET_CLOSED);
                LocalBroadcastManager.getInstance(this).sendBroadcast(socketBroadcast);
            }

        }
    } catch (IOException e) {
        Log.e("GDMService", e.toString());
    }

}