I have written UDP server client program. The problem that i am facing is that when i am running server program, it is not waiting for client to connect. Whole code is executing after running till the end. And when i am running client side in between of execution of server side, client side is receiving data from its point of execution. Here is my server code-
public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(4321); byte[] sendData; String sentence = null; FileInputStream file = new FileInputStream(new File("E:\\Deepak.txt")); InetAddress IPAddress=InetAddress.getByName("localhost"); BufferedReader in = new BufferedReader(new InputStreamReader(file)); do{ while((sentence = in.readLine()) != null) { Thread.sleep(3000); System.out.println(sentence); sendData = sentence.getBytes(); DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length,IPAddress,9876); serverSocket.send(sendPacket); } }while(true); } Here is my client side code-
public static void main(String args[]) throws SocketException, UnknownHostException, IOException { DatagramSocket clientSocket = new DatagramSocket(); byte[] receiveData = new byte[1024]; String sentence ; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); receivePacket.getLength(); System.out.println(receivePacket.getLength()); clientSocket.receive(receivePacket); sentence = new String( receivePacket.getData()); } }