Reputation: 535
I have the following UDP client and servcer classes and I am trying to send some string from the UDPClient
to the another class 'UDPServer' in the same java project at the localhost and port 7777. I am facing problem that I am not receiving anything in the UDPServer class from the UDPClient class. Does anyone have an idea where the problem is?
I appreciate any help!
UDPClient
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class UDPClient {
public static void main(String args[]) throws Exception {
String aString = "Hello World";
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
sendData = aString.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7777);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
UDPServer
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class UDPServer {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(7777);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
Upvotes: 1
Views: 148
Reputation: 1330
Hi try to check what wrong with port allocation, because you code works ok.
Start your server and run this command:
Windows
netstat -aon | FINDSTR 7777
Linux:
netstat -aon | grep 7777
You should see the PID check if pid is same as UDPServer runs on. Also check firewall maybe there is something wrong?
Upvotes: 1