I have UDP socket as below. I need to send back data to the client. I tried to capture both the ip and port but it shows me as Port is : -1 and InetAddress : null. What can I do to rectify on this?
class ReceiverThread implements Runnable {
private DatagramSocket receivedSocketConn1;
ReceiverThread(DatagramSocket receivedSocketConn1) {
System.out.println("Thread Received");
this.receivedSocketConn1=receivedSocketConn1;
}
public void run(){
while (true){
try{
InetAddress IPAddress = receivedSocketConn1.getInetAddress();
int port = receivedSocketConn1.getPort();
final byte[] buffer = new byte[1024];
final DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
receivedSocketConn1.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
byte[] sendData = new byte[50];
String capitalizedSentence = "OK\r\n\n";
sendData = capitalizedSentence.getBytes();
System.out.println("Port is : "+port);
System.out.println("InetAddress : "+IPAddress);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
receivedSocketConn1.send(sendPacket);
}
catch(Exception e){
System.out.println("MyError:Socket Accepting has been caught in main loop."+e.toString());
e.printStackTrace(System.out);
}
}
}
}
public static void main(String[] args) {
new commUDP9000();
}
commUDP9000() {
try{
final DatagramSocket serverSocketConn = new DatagramSocket (9000);
new Thread(new ReceiverThread(serverSocketConn)).start();
}
catch (Exception e)
{
System.out.println("MyError:Socket Conn has been caught in main loop."+e.toString());
e.printStackTrace(System.out);
//System.exit(0);
}
}
}