Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Data Communication & Networking I week 4 Practical Lecture

UDP Chat
UDP stands for User Datagram Protocol, a connectionless transport layer protocol.
It implements multicasting and the sending messages called datagrams which
considered a best-effort mode of communications.
Server Side:
DatagramSocket  This class represents a socket for sending and receiving
datagram packets. A datagram socket is the sending or receiving point for a packet
delivery service. Each packet sent or received on a datagram socket is individually
addressed and routed. Multiple packets sent from one machine to another may be
routed differently, and may arrive in any order. It constructs a datagram socket and
binds it to the specified port on the local host machine.
DatagramPacket  This class represents a datagram packet. Datagram packets are
used to implement a connectionless packet delivery service. Each message is routed
from one machine to another based solely on information contained within that
packet. Multiple packets sent from one machine to another might be routed
differently, and might arrive in any order. Packet delivery is not guaranteed. It
constructs a DatagramPacket for receiving packets of length length. The length
argument must be less than or equal to msgIn.length. msgIn is a buffer for holding
the incoming datagram. Or it constructs a datagram packet for sending packets of
length length to the specified port number on the specified host. The length argument
must be less than or equal to msgOut.length.
String  The String class represents character strings. All string literals in Java
programs, such as "abc", are implemented as instances of this class. The class String
includes methods for examining individual characters of the sequence, for
comparing strings, for searching strings, for extracting substrings, and for creating a
copy of a string with all characters translated to uppercase or to lowercase. The
String class provides methods for dealing with Unicode code points (i.e., characters),
in addition to those for dealing with Unicode code units (i.e., char values). It
constructs a new String by decoding the specified subarray of bytes using the
platform's default charset. The length of the new String is a function of the charset,
and hence may not be equal to the length of the subarray. Firstly get the data in byte,
secondly starts from the offset in the buffer until it length long.

The used functions when you create objects are as follow:


1. receive()  Receives a datagram packet from this socket. When this method
returns, the DatagramPacket's buffer is filled with the data received. The

1|P ag e By: Ghasaq Bahaa


Data Communication & Networking I week 4 Practical Lecture

datagram packet also contains the sender's IP address, and the port number on
the sender's machine. This method blocks until a datagram is received. The
length field of the datagram packet object contains the length of the received
message. If the message is longer than the packet's length, the message is
truncated.
2. getData()  Returns the data buffer. The data received or the data to be sent
starts from the offset in the buffer, and runs for length long.
3. getLength()  Returns the length of the data to be sent or the length of the
data received.
4. getPort()  Returns the port number on the remote host to which this
datagram is being sent or from which the datagram was received.
5. getAddress()  Returns the IP address of the machine to which this datagram
is being sent or from which the datagram was received.
6. getBytes()  Encodes this String into a sequence of bytes using the platform's
default charset, storing the result into a new byte array.
7. Send()  Sends a datagram packet from this socket. The DatagramPacket
includes information indicating the data to be sent, its length, the IP address
of the remote host, and the port number on the remote host.
Code:

2|P ag e By: Ghasaq Bahaa


Data Communication & Networking I week 4 Practical Lecture

Notes:
1. Do while has been used in this program for sending multiple messages
without exit while the condition is true. Which means until you close it, it
will listen on the specified port and you cannot re-run it on the same port.
2. The ports that you can used in order to listen are in range of (1024-65535).
Client Side:
Same classes will be used for establishing connection, sending and receiving
messages.
byte[]  byte arrays are often used in Java to temporarily store data internally in an
application. The byte as data type is an 8-bit signed two's complement integer and it
has a minimum value of -128 and a maximum value of 127 (inclusive) which can be
useful for saving memory in large arrays, where the memory savings actually
matters. The byte buffer (the byte array) is the data that is to be sent in the UDP
datagram. The length of the used buffer 1024 bytes, is the maximum amount of data
you can send in a single UDP packet.
getLocalHost()  Returns the address of the local host (PC name and IP). This is
achieved by retrieving the name of the host from the system, then resolving that
name into an InetAddress. (Lecture 1)
Code:

3|P ag e By: Ghasaq Bahaa


Data Communication & Networking I week 4 Practical Lecture

Notes:
1. Classes and function is used to do the same functionality in the server and
the client. You can read them in the server explanations above.
2. Scanner has been used to read the client message and then send it to the
server after convert it into byte.
3. The server replies with “ok” message and you can change it to send a
message same as the client using scanner (try it yourself).
4. Read Arrays (1D & 2D “Dimensional”) with different types defining (string,
int, byte and etc.) in order to be created, sent and received.
References:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
https://www.tutorialspoint.com/java/java_networking.htm
http://tutorials.jenkov.com/java-networking/udp-datagram-sockets.html
https://docs.oracle.com/javase/7/docs/api/java/net/DatagramPacket.html
https://docs.oracle.com/javase/7/docs/api/java/net/DatagramSocket.html
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Appendix 1:
Server code:
package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class server {
public static void main(String[] args) throws IOException {
int port = 1234;
DatagramSocket socket = new DatagramSocket(port);
System.out.println("open connection ");
do {
DatagramPacket inPacket, outPacket;
byte[] msgIn = new byte[1024];
String msgOut = "OK! " ;
inPacket = new DatagramPacket(msgIn, msgIn.length);
socket.receive(inPacket);
String sentense = new String(inPacket.getData(), 0, inPacket.getLength());

4|P ag e By: Ghasaq Bahaa


Data Communication & Networking I week 4 Practical Lecture

System.out.println("data from client : " + sentense);


int portClient = inPacket.getPort();
InetAddress address = inPacket.getAddress();
outPacket = new DatagramPacket(msgOut.getBytes(), msgOut.length(), address, portClient);
socket.send(outPacket);
System.out.println("Server >"+msgOut);
} while (true);
}
}

Appendix 2:
Client code:
package udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Client {
public static void main(String[] args) throws SocketException, IOException {
int port = 1234;
InetAddress addressServer = InetAddress.getLocalHost();
System.out.println(" find ip address ");
DatagramPacket inPacket, outPacket;
Scanner s = new Scanner(System.in);
String msgOut = "";
byte[] msgIn = new byte[1024];
DatagramSocket socket = new DatagramSocket();
while (!msgOut.equals("close")) {
System.out.print("Enter message : ");
msgOut = s.nextLine();
outPacket = new DatagramPacket(msgOut.getBytes(), msgOut.length(), addressServer, port);
socket.send(outPacket);
inPacket = new DatagramPacket(msgIn , msgIn.length);
socket.receive(inPacket);
String str = new String(inPacket.getData(), 0, inPacket.getLength());
System.out.println("Server > " + str);
}
}
}

5|P ag e By: Ghasaq Bahaa

You might also like