Code example for DatagramSocket

Methods: close, send, setBroadcast, setSoTimeout

2
    private void threadForUdpClient() { 
        new Thread() {
            @Override 
            public void run() { 
                try { 
                    DatagramSocket socket = new DatagramSocket();
                    socket.setBroadcast(true);
                    socket.setSoTimeout(5000);
 
                    sendDiscoveryRequest(socket);
 
                    listenForResponses(socket);
                    Log.i("test", "udp client close...");
                    socket.close();
                } catch (SocketException e) {
                    // TODO Auto-generated catch block 
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block 
                    e.printStackTrace();
                } 
            } 
        }.start();
    } 
 
    private InetAddress getBroadcastAddress() throws IOException {
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        DhcpInfo dhcp = wifi.getDhcpInfo();
        if (dhcp == null) {
            Log.d("test", "Could not get dhcp info");
            return null; 
        } 
 
        int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
        byte[] quads = new byte[4];
        for (int k = 0; k < 4; k++) {
            quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
        } 
        return InetAddress.getByAddress(quads);
    } 
 
    private void sendDiscoveryRequest(DatagramSocket socket) throws IOException {
        String data = "DISCOVER_SERVER_REQUEST";
 
        DatagramPacket packet = new DatagramPacket(data.getBytes(),
                data.length(), getBroadcastAddress(), UDP_PORT);
 
        socket.send(packet);
    } 
 
    protected void listenForResponses(DatagramSocket socket) throws SocketException {
        // TODO Auto-generated method stub 
        byte buf[] = new byte[1024];