Question

Hi there currently i am creating a UDP connection for my program currently its localhost how am i going to insert my IP address so that another computer in the same network will be able to receive the message i type at the server side.

UDPSERVER
package testing;

import java.io.*;
import java.net.*;
public class UdpServer {

    public static void main(String args[]) {
        String str;
        try {
            BufferedReader Br;
            Br = new BufferedReader(new InputStreamReader(System. in ));
            DatagramSocket Sock;
            Sock = new DatagramSocket(1000);
            DatagramPacket Dp;
            System.out.println("Enter the data..... Enter 'exit' to stop");
            while (true) {
                str = Br.readLine();
                Dp = new DatagramPacket(str.getBytes(), str.length(),
                    InetAddress.getByName("localhost"), 2000);
                Sock.send(Dp);
                if (str.equals("exit")) break;
            }
            Sock.close();
        } catch (Exception e) {}
    }
}

UdpClient
package testing;
import java.net.*;
public class UdpClient {
    public static void main(String arg[]) {
        String str;
        DatagramSocket Sock;
        DatagramPacket Dp;
        try {
            Sock = new DatagramSocket(2000);
            byte Buff[] = new byte[1024];
            System.out.println("Client ready...");
            while (true) {
                Dp = new DatagramPacket(Buff, 1024);
                Sock.receive(Dp);
                str = new String(Dp.getData(), 0, Dp.getLength());
                System.out.println(str);
                if (str.equals("exit")) break;
            }
            Sock.close();
        } catch (Exception e) {
            System.out.println("Connection failure...");
        } finally {
            System.out.println("Server Disconnected...");
        }
    }
}
Was it helpful?

Solution

The first step is to try and hardcode the ip of the other computer and test. If that works then look at adding UDP Broadcast Discovery. Here's an example in java: http://michieldemey.be/blog/network-discovery-using-udp-broadcast/

The idea is that all devices that need to talk broadcast on UDP. Once they hear the broadcast, they need to connect to eachother. Usually one side will need to be pre-determined as the server, and the other as the client.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top