My UDP client will continuously send “Hello Server!” every 2 seconds to the UDP server (who just echos the message but in uppercase). They will both print what they’ve received.
My problem is that I would always have to run the server first then the client. If I run the client then server, the server would not receive anything at all. I want the server to start any time he wants and still receive packets from the client. How can I do this?
UDPClient:
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
while(true) {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[100];
byte[] receiveData = new byte[100];
String sentence = "Hello Server!";
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
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();
Thread.sleep(2000);
}
}
}
UDPServer:
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[100];
byte[] sendData = new byte[100];
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);
}
}
}
If you run the client first it will get an exception
PortUnreachableExceptionand the client program will close, in order for that not to happen you have to catch the exception so the client keeps on running.try: