Reputation: 441
I am trying to receive a simple string using DatagramPacket
and DatagramSocket
class in Java.
Here is my code:
public static void main(String [] args){
DatagramSocket aSocket = null;
try{
aSocket= new DatagramSocket();
String aMessage = "my message";
System.out.println("1");
byte [] m = aMessage.getBytes();
InetAddress aHost = InetAddress.getByName("localhost");
int serverPort = 6789;
DatagramPacket request = new DatagramPacket(m,aMessage.length(),aHost,serverPort);
System.out.println("2");
aSocket.send(request);
System.out.println("3");
byte [] buffer = new byte[1000];
System.out.println("4");
DatagramPacket reply = new DatagramPacket(buffer,buffer.length);
aSocket.receive(reply);
System.out.println("5");
System.out.println("DATA RECEIVED" + reply.getData());
aSocket.close();
}
catch(SocketException ex){
ex.printStackTrace();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
It's not printing the received data. I have put System.out.println
just to see where the code is executed, and it stops at 4, it does not print 5, meaning the problem is just below 4. Why am I not receiving the data, can anybody help me with this please?
Upvotes: 2
Views: 7982
Reputation:
@avi dont use the same datagram socket for getting rely. For getting reply you have to mention the port nomber of the server datagram socket.use
DatagramSocket datagramSocket = new DatagramSocket(6789);// Which is given by you only
then use datagramSocket.receive(reply);
and also for getting address use this method
InetAddress aHost = InetAddress.getLocalHost();
instead of
InetAddress aHost = InetAddress.getByName("localhost");
Take a refrence of this link
Upvotes: 3