DatagramSockets are Java’s mechanism for network communication via UDP instead of TCP. Java provides DatagramSocket to communicate over UDP instead of TCP. It is also built on top of IP. DatagramSockets can be used to both send and receive packets over the Internet.
One of the examples where UDP is preferred over TCP is the live coverage of TV channels. In this aspect, we want to transmit as many frames to live audience as possible not worrying about the loss of one or two frames. TCP being a reliable protocol add its own overhead while transmission.
Another example where UDP is preferred is online multiplayer gaming. In games like counter-strike or call of duty, it is not necessary to relay all the information but the most important ones. It should also be noted that most of the applications in real life uses careful blend of both UDP and TCP; transmitting the critical data over TCP and rest of the data via UDP.
This article is a simple implementation of one-sided client-server program wherein the client sends messages to server and server just prints it until the client sends “bye”.
Java Datagram programming model Steps
- Creation of DatagramSocket:- First, a datagramSocket object is created to carry the packet to the destination and to receive it whenever the server sends any data. To create a datagramSocket following constructors can be used:
protected DatagramSocket DatagramSocket():
Syntax: public DatagramSocket() throws SocketException Creates a datagramSocket and binds it to any available port on local machine. If this constructor is used, the OS would assign any port to this socket.
- protected DatagramSocket DatagramSocket(int port):-
Syntax: public DatagramSocket(int port) throws SocketException Parameters: port - port to which socket is to be bound Throws: SocketException - If the socket cannot be bound to the specific local port. Creates a DatagramSocket and binds to the specified port on the local machine.
- protected DatagramSocket DatagramSocket(int port, InetAddress inetaddress):-
Syntax: public DatagramSocket(int port, InetAddress inetaddress) throws SocketException Parameters: port - port to which socket is to be bound. inetaddress - local address to which socket is to be bound. Throws: SocketException - If the socket cannot be bound to the specific local port. It creates a DatagramSocket and binds it to specified port and ip-address.
- protected DatagramSocket DatagramSocket():
- Creation of DatagramPacket: In this step, the packet for sending/receiving data via a datagramSocket is created.
- Constructor to send data:
DatagramPacket(byte buf, int length, InetAddress inetaddress, int port):-
Syntax: public DatagramPacket(byte buf, int offset, int length, SocketAddress address) Parameters: buf - the packet data. offset - the packet data offset. length - the packet data length. address - the destination socket address. Constructs a DatagramPacket for sending data at specified address and specified port.
- Constructor to receive the data:
DatagramPacket(byte buf, int length):-
Syntax: public DatagramPacket(byte buf, int length) Parameters: buf - the packet data. length - the packet data length. Constructs a DatagramPacket for recieving the data of length length in the byte array buf.
- Constructor to send data: DatagramPacket(byte buf, int length, InetAddress inetaddress, int port):-
- Invoke a send() or receive() call on socket object
Syntax: void send(DatagramPacket packet) throws SocketException Parameters: packet - Datagrampacket to send. Throws: SocketException - If there is an error in binding. IllegalArgumentException - if address is not supported by the socket.
Syntax: void receive(DatagramPacket packet) throws SocketException Parameters: packet - Datagrampacket to receive from this socket. Throws: SocketException - If there is an error in binding. IllegalArgumentException - if address is not supported by the socket.
Client Side Implementation
Hello I am Client. ... bye
Server side Implementation
In a nutshell, we can summarize the steps of sending and recieving data over UDP as follows:-
- For sending a packet via UDP, we should know 4 things, the message to send, its length, ipaddress of destination, port at which destination is listening.
- Once we know all these things, we can create the socket object for carrying the packets and packets which actually possess the data.
- Invoke send()/receive() call for actually sending/recieving packets.
- Extract the data from the received packet.
Client:- Hello Client:- I am client. ... Client:- bye Client sent bye.....EXITING
Note:- In order to test the above programs on the system, Please make sure that you run the server program first and then the client one. Make sure you are in the client console and from there keep on typing your messages each followed with a carriage return. Every time you send a message you will be redirected to the server console depending on your environment settings. If not redirected automatically, switch to server console to make sure all your messages are received. Finally to terminate the communication, type "bye" (without quotes) and hit enter.
As an enthusiastic reader you should also try and implement a two way chat application wherein the server will be able to respond to messages as and when he likes.
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Internal working of Set/HashSet in Java
- Internal Working of HashMap in Java
- Working with JAR and Manifest files In Java
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java.util.BitSet class methods in Java with Examples | Set 2
- Java.util.function.DoublePredicate interface in Java with Examples
- Java.util.function.LongPredicate interface in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
- Java.util.concurrent.RecursiveAction class in Java with Examples
- Java.util.function.IntPredicate interface in Java with Examples
- Java.util.function.BiPredicate interface in Java with Examples
- Java lang.Long.numberOfLeadingZeros() method in Java with Examples
- Java lang.Long.highestOneBit() method in Java with Examples
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
- Java.util.concurrent.RecursiveTask class in Java with Examples
Improved By : MarkShanks