In this post, we will see UDP Client Server Program in Java (Socket Programming).
UDP is connection less protocol. Here, no connection is established between Client and Server. Client and Server have to create Datagram Packet and also have to mention IP address and Port number.
Go through the following programs.
Note: First run UDPServer.java and then UDPClient.java in another terminal tab/window.
Program (UDPServer.java)
import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(7009); 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()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length, IPAddress,port); System.out.println("Sending Capitalized message to Client"); serverSocket.send(sendPacket); } } } |
Output (UDPServer.java):
parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ javac UDPServer.java parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ java UDPServer Sending Capitalized message to Client |
Program (UDPClient.java)
import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { System.out.println("Enter any message:"); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("localhost"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length, IPAddress, 7009); 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(); } } |
Output (UDPClient.java):
parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ javac UDPClient.java parag@parag-Inspiron-N4010:~/Desktop/programs/socket$ java UDPClient Enter any message: hello FROM SERVER:HELLO |
No comments:
Post a Comment