SlideShare a Scribd company logo
UDP Programming
Overview
Overview UDP communication can be more efficient than guaranteed-delivery data streams . If the amount of data is small and the data is sent frequently, it may make sense to avoid the overhead of guaranteed delivery. Unlike TCP streams, which establish a connection, UDP causes fewer overheads . If the amount of  data being sent is small  and the data is sent  infrequently , the  overhead  of  establishing  a connection might not be worth it. Real-time applications that demand up-to-the-second or better performance may be candidates for UDP, as there are fewer delays due to the error checking and flow control of TCP . UDP packets can be used to saturate available network bandwidth to deliver large amounts of data (such as streaming  video/audio , or telemetry data for a multiplayer network game). In addition, if  some data is lost , it can be replaced by the next set of packets with updated information, eliminating the need to resend old data that is now out of date. UDP sockets can receive data from more than one host machine . If several machines must  be communicated with, then UDP may be more convenient than other mechanisms such as TCP.
DatagramPacket Class Port (Remote Port) DataPacket(port) … setPort(port)
Creating a DatagramPacket Constructor requires the specification of a byte array, which will be used to store the UDP packet contents, and the length of the data packet . There are two reasons to create a new DatagramPacket: 1.To send data to a remote machine using UDP DatagramPacket(byte[] buffer, int length, InetAddress dest_addr, int dest_port).  For example: InetAddress addr = InetAddress.getByName("192.168.0.1"); DatagramPacket packet = new DatagramPacket ( new byte[128],128, addr, 2000); 2.To receive data sent by a remote machine using UDP DatagramPacket(byte[] buffer, int length). For example: DatagramPacket packet = new DatagramPacket(new byte[256], 256);
Using a DatagramPacket InetAddress   getAddress () — returns the IP address from which a DatagramPacket was sent, or (if the packet is going to be sent to a remote machine), the destination IP address. byte[]   getData() —  returns the contents of the DatagramPacket, represented as an array of bytes. int   getLength() —  returns the length of the data stored in a DatagramPacket. This can be less than the actual size of the data buffer. int   getPort() —  returns the port number from which a DatagramPacket was sent,or (if the packet is going to be sent to a remote machine), the destination port number.
Using a DatagramPacket void   setAddress(InetAddress   addr) —  assigns a new destination address to a DatagramPacket. void   setData(byte[]   buffer )—  assigns a new data buffer to the DatagramPacket. Remember to make the buffer long enough, to prevent data loss. void   setLength(int   length) —  assigns a new length to the DatagramPacket. Remember that the length must be less than or equal to the maximum size of the data buffer, or an IllegalArgumentException will be thrown. When sending a smaller amount of data, you can adjust the length to fit—you do not need to resize the data buffer. void setPort(int port)—  assigns a new destination port to a DatagramPacket.
DatagramSocket Class The DatagramSocket class provides access to a UDP socket, which allows UDP packets to be sent and received . A DatagramPacket is used to represent a UDP packet, and must be created prior to receiving any packets. The same DatagramSocket can be used to receive packets as well as to send them. However, read operations are blocking, meaning that the application will continue to wait until a packet arrives. A DatagramSocket can be used to both send and receive packets.  Each DatagramSocket binds to a port on the local machine, which is used for addressing packets . The application is a UDP  server , it will usually  choose a specific port number . If the DatagramSocket is intended to be a  client , and doesn't need to bind to a specific port number, a  blank constructor can be specified .
Creating a DatagramSocket To create a client  DatagramSocket , the following constructor is used:  DatagramSocket ()  throws  java.net.SocketException .  To create a server  DatagramSocket , the following constructor is used, which takes as a parameter the port to which the UDP service will be bound:  DatagramSocket(int   port )  throws  java.net.SocketException .  Although rarely used, there is a third constructor for  DatagramSocket .  If a machine is known by several IP addresses, you can specify the IP address and port to which a UDP service should be bound. It takes as parameters the port to which the UDP service will be bound, as well as the  InetAddress   of the service. This constructor is: DatagramSocket  ( int   port ,  InetAddress   addr ) throwsjava.net.SocketException . Port is Local !!!
Using a DatagramSocket void close()—  closes a socket, and unbinds it from the local port. void connect(InetAddress remote_addr int remote_port)—  restricts access to the specified remote address and port. The designation is a misnomer, as UDP doesn't actually create a "connection" between one machine and another. void   disconnect()—  disconnects the DatagramSocket and removes any restrictions imposed on it by an earlier connect operation. !!! Sai InetAddress getInetAddress()— returns the remote address to which the socket is connected, or null if no such connection exists. int   getPort ()— returns the remote port to which the socket is connected, or –1 if no  such connection exists. InetAddress   getLocalAddress()—  returns the local address to which the socket is bound. int   getLocalPort ()— returns the local port to which the socket is bound. int   getReceiveBufferSize () throws java.net.SocketException— returns the maximum buffer size used for incoming UDP packets.
Using a DatagramSocket int getSendBufferSize()  throws java.net.SocketException— returns the maximum buffer size used for outgoing UDP packets. int   getSoTimeout()  throws java.net.SocketException— returns the value of the timeout socket option. By default, this value will be zero, indicating that blocking I/O will be used. void receive(DatagramPacket packet)  throws java.io.IOException— reads a UDP packet and stores the contents in the specified packet. The address and port fields of the packet will be overwritten with the sender address and port fields, and the length field of the packet will contain the length of the original packet, which can be less than the size of the packet's byte-array. If a timeout value has been specified, a java.io.InterruptedIOException will be thrown if the time is exceeded. void send(DatagramPacket packet)  throws java.io.IOException— sends a UDP packet, represented by the specified packet parameter.
Using a DatagramSocket void setReceiveBufferSize(int length)  throws java.net.SocketException— sets the maximum buffer size used for incoming UDP packets. Whether the specified length will be adhered to is dependent on the operating system. void setSendBufferSize(int length)  throws java.net.SocketException— sets the maximum buffer size used for outgoing UDP packets. Whether the specified length will be adhered to is dependent on the operating system. void setSoTimeout(int duration)  throws java.net.SocketException— sets the value of the timeout socket option. This value is the number of milliseconds a read operation will block before throwing a java.io.InterruptedIOException.
Listening for UDP Packets UDP packets are received by a DatagramSocket and  translated into a DatagramPacket object. When an application wishes to read UDP packets, it calls the DatagramSocket.receive method, which copies a UDP packet into the specified DatagramPacket. The contents of the DatagramPacket are processed, and the process is repeated as needed.
Listening for UDP Packets DatagramPacket  packet  = new DatagramPacket ( new  byte[256],  256 ); DatagramSocket  socket  = new DatagramSocket( 2000 ); boolean finished = false; while (! finished ){ socket.receive (packet); // process the packet } socket.close(); When processing the packet,  the application must work directly with an array of bytes . If, however, your application is better suited to reading text, you can use classes from the Java I/O package to convert between a byte array and another type of stream or reader. By hooking a  ByteArrayInputStream   to the contents of a datagram and then to another type of  InputStream   or an  InputStreamReader , you can access the contents of UDP packets relatively easily. Many developers prefer to use Java I/O streams to process data, using a  DataInputStream   or a  BufferedReader   to access the contents of byte arrays.
Listening for UDP Packets ByteArrayInputStream  bin = new  ByteArrayInputStream( packet.getData()  ); DataInputStream  din = new DataInputStream (bin); // Read the contents of the UDP packet .......
Sending UDP packets
Sending UDP packets DatagramSocket socket = new DatagramSocket(); DatagramPacket packet = new DatagramPacket (new  byte[256],256); packet.setAddress (InetAddress.getByName (someServer)); packet.setPort (2000); boolean finished = false; while !finished ){ // Write data to packet buffer ......... packet.setData(…..); packet.setLength(…); socket.send (packet); // Do something else, like read other packets, or check to // see if no more packets to send ......... } socket.close();
UDP PacketReceiveDemo - Server The application starts by binding to a specific port, 2000. Applications offering a service generally bind to a specific port. When acting as a receiver, your application should choose a specific port number, so that a sender can send UDP packets to this port. Next, the application prepares a  DatagramPacket  for storing UDP packets, and creates a new buffer for storing packet data. // Create a datagram socket, bound to the specific port 2000 DatagramSocket socket = new DatagramSocket(2000); System.out.println ("Bound to local port " + socket.getLocalPort()); // Create a datagram packet, containing a maximum buffer of 256 bytes DatagramPacket packet = new DatagramPacket(new byte[256],  256);
UDP PacketReceiveDemo - Server Now the application is ready to read a packet. The read operation is blocking, so until a packet arrives, the server will wait. When a packet is successfully delivered to the application, the addressing information for the packet is displayed so that it can be determined where it came from. // Receive a packet - remember by default this is a blocking // operation socket.receive(packet); // Display packet information InetAddress remote_addr = packet.getAddress(); System.out.println ("Sent by : " +  remote_addr.getHostAddress() ); System.out.println ("Send from: " + packet.getPort());
UDP PacketReceiveDemo - Server To provide easy access to the contents of the UDP packet, the application uses a  ByteArrayInputStream a DataInputStream  to read from the packet. Reading one character at a time, the program displays the contents of the packet and then finishes. // Display packet contents, by reading from byte array DataInputStream din = new DataInputStream(new  ByteArrayInputStream(packet.getData())); // Display only up to the length of the original UDP packet for (int i = 0; i < packet.getLength()/2; i++) { System.out.print(din.readChar()); } socket.close(); }
UDP PacketSendDemo - Client The application starts by binding a UDP socket to a local port, which will be used to send the data packet. Unlike the receiver demonstration, it doesn't matter which local port is being used. In fact, any free port is a candidate, and you may find that running the application several times will result in different port numbers. After binding to a port, the port number is displayed to demonstrate this. // Create a datagram socket, bound to any available local port DatagramSocket socket = new DatagramSocket(); System.out.println (&quot;Bound to local port &quot; + socket.getLocalPort()); Before sending any data, we need to create a  DatagramPacket . First, a  ByteArrayOutputStream  is used to create a sequence of bytes. Once this is complete, the array of bytes is passed to the  DatagramPacket  constructor.
UDP PacketSendDemo - Client // Create a message to send using a UDP packet ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); dout.writeChars(&quot;Greetings!&quot;); // Get the contents of our message as an array of bytes byte[] barray = bout.toByteArray(); // Create a datagram packet, containing our byte array DatagramPacket packet = new DatagramPacket(barray,  barray.length); Now that the packet has some data, it needs to be correctly addressed. As with a postal message, if it lacks correct address information it cannot be delivered. We start by obtaining an  InetAddress   for the remote machine, and then display its IP address. This  InetAddress   is passed to the  setAddress   method of  DatagramPacket , ensuring that it will arrive at the correct machine. However, we must go one step further and specify a port  number. In this case, port 2000 is matched, as the receiver will be bound to that port.
UDP PacketSendDemo - Client System.out.println (&quot;Looking up hostname &quot; + hostname ); // Lookup the specified hostname, and get an InetAddress InetAddress remote_addr =  InetAddress.getByName(hostname); System.out.println (&quot;Hostname resolved as &quot; + remote_addr.getHostAddress()); // Address packet to sender packet.setAddress (remote_addr); // Set port number to 2000 packet.setPort (2000); // Send the packet - remember no guarantee of delivery socket.send(packet);

More Related Content

PPTX
#2 (UDP)
ODP
Sockets and Socket-Buffer
PPTX
#1 (TCPvs. UDP)
PPTX
Network emulator
DOC
Mikro tik
PPT
IPV6 Flow Labels
DOCX
Lab 4 final report
PPTX
Protocol implementation on NS2
#2 (UDP)
Sockets and Socket-Buffer
#1 (TCPvs. UDP)
Network emulator
Mikro tik
IPV6 Flow Labels
Lab 4 final report
Protocol implementation on NS2

What's hot (20)

PPT
Simulation and Performance Analysis of AODV using NS-2.34
PDF
Tcpdump
PPT
I Pv6 Extension Headers
PDF
Wireshark tcp
PDF
Zenoh Tutorial
PPTX
IPC SOCKET
PDF
Wireshark tcp - 2110165028
PDF
Wireshark udp solution
PPT
PDF
MPEG DASH White Paper
PPTX
hajer
PPSX
Internetworking - IP
PDF
PPT
Tuning 17 march
PPTX
Part 12 : Local Area Networks
PPTX
Part 6 : Internet applications
PPTX
Basics of sockets
PPTX
Client server examples for tcp abnormal conditions
PPT
Introduction P2p
Simulation and Performance Analysis of AODV using NS-2.34
Tcpdump
I Pv6 Extension Headers
Wireshark tcp
Zenoh Tutorial
IPC SOCKET
Wireshark tcp - 2110165028
Wireshark udp solution
MPEG DASH White Paper
hajer
Internetworking - IP
Tuning 17 march
Part 12 : Local Area Networks
Part 6 : Internet applications
Basics of sockets
Client server examples for tcp abnormal conditions
Introduction P2p
Ad

Viewers also liked (20)

PPT
Wire Less
PPT
PPT
Net Admin Intro
PPT
Call Back
PPT
Lession3 Routing
PPT
Lession1 Linux Preview
PPT
Lession2 Xinetd
PPT
PPT
Net Security Intro
PPT
Module 7 Sql Injection
PPT
Module 1 Introduction
PPT
Call Back
PPT
PPT
Url Connection
PPT
Lession4 Dhcp
PPT
Module 3 Scanning
PPT
Module 9 Dos
PPTX
PPT
Iptables
ODP
Nmap Scripting Engine and http-enumeration
Wire Less
Net Admin Intro
Call Back
Lession3 Routing
Lession1 Linux Preview
Lession2 Xinetd
Net Security Intro
Module 7 Sql Injection
Module 1 Introduction
Call Back
Url Connection
Lession4 Dhcp
Module 3 Scanning
Module 9 Dos
Iptables
Nmap Scripting Engine and http-enumeration
Ad

Similar to Udp Programming (20)

PPT
UDP-Dept Businesss Computing university .ppt
PDF
Lecture6
PDF
Chapter 3 : User Datagram Protocol (UDP)
PPT
Network programming in Java
PPTX
Advance Java-Network Programming
PPTX
Javanetworkingbasicssocketsoverview
PPTX
Java networking basics & sockets overview
PPT
Easy Steps to implement UDP Server and Client Sockets
PPT
Md13 networking
PPTX
PDF
Java- Datagram Socket class & Datagram Packet class
PPTX
Java socket presentation
PPTX
Networking in Java
PDF
Java Programming - 07 java networking
PDF
28 networking
PPT
Network Programming in Java
PPT
Network programming in Java
PPT
Networking
PPT
TCP IP
PPTX
Datagrams
UDP-Dept Businesss Computing university .ppt
Lecture6
Chapter 3 : User Datagram Protocol (UDP)
Network programming in Java
Advance Java-Network Programming
Javanetworkingbasicssocketsoverview
Java networking basics & sockets overview
Easy Steps to implement UDP Server and Client Sockets
Md13 networking
Java- Datagram Socket class & Datagram Packet class
Java socket presentation
Networking in Java
Java Programming - 07 java networking
28 networking
Network Programming in Java
Network programming in Java
Networking
TCP IP
Datagrams

More from leminhvuong (11)

PPT
Module 10 Physical Security
PPT
Module 8 System Hacking
PPT
Module 6 Session Hijacking
PPT
Module 5 Sniffers
PPT
Module 4 Enumeration
PPT
Module 2 Foot Printing
PPT
Module 1 Introduction
PPT
Call Back
PPT
Socket Programming
PPT
Scrollable Updatable
PPT
Module 10 Physical Security
Module 8 System Hacking
Module 6 Session Hijacking
Module 5 Sniffers
Module 4 Enumeration
Module 2 Foot Printing
Module 1 Introduction
Call Back
Socket Programming
Scrollable Updatable

Udp Programming

  • 3. Overview UDP communication can be more efficient than guaranteed-delivery data streams . If the amount of data is small and the data is sent frequently, it may make sense to avoid the overhead of guaranteed delivery. Unlike TCP streams, which establish a connection, UDP causes fewer overheads . If the amount of data being sent is small and the data is sent infrequently , the overhead of establishing a connection might not be worth it. Real-time applications that demand up-to-the-second or better performance may be candidates for UDP, as there are fewer delays due to the error checking and flow control of TCP . UDP packets can be used to saturate available network bandwidth to deliver large amounts of data (such as streaming video/audio , or telemetry data for a multiplayer network game). In addition, if some data is lost , it can be replaced by the next set of packets with updated information, eliminating the need to resend old data that is now out of date. UDP sockets can receive data from more than one host machine . If several machines must be communicated with, then UDP may be more convenient than other mechanisms such as TCP.
  • 4. DatagramPacket Class Port (Remote Port) DataPacket(port) … setPort(port)
  • 5. Creating a DatagramPacket Constructor requires the specification of a byte array, which will be used to store the UDP packet contents, and the length of the data packet . There are two reasons to create a new DatagramPacket: 1.To send data to a remote machine using UDP DatagramPacket(byte[] buffer, int length, InetAddress dest_addr, int dest_port). For example: InetAddress addr = InetAddress.getByName(&quot;192.168.0.1&quot;); DatagramPacket packet = new DatagramPacket ( new byte[128],128, addr, 2000); 2.To receive data sent by a remote machine using UDP DatagramPacket(byte[] buffer, int length). For example: DatagramPacket packet = new DatagramPacket(new byte[256], 256);
  • 6. Using a DatagramPacket InetAddress getAddress () — returns the IP address from which a DatagramPacket was sent, or (if the packet is going to be sent to a remote machine), the destination IP address. byte[] getData() — returns the contents of the DatagramPacket, represented as an array of bytes. int getLength() — returns the length of the data stored in a DatagramPacket. This can be less than the actual size of the data buffer. int getPort() — returns the port number from which a DatagramPacket was sent,or (if the packet is going to be sent to a remote machine), the destination port number.
  • 7. Using a DatagramPacket void setAddress(InetAddress addr) — assigns a new destination address to a DatagramPacket. void setData(byte[] buffer )— assigns a new data buffer to the DatagramPacket. Remember to make the buffer long enough, to prevent data loss. void setLength(int length) — assigns a new length to the DatagramPacket. Remember that the length must be less than or equal to the maximum size of the data buffer, or an IllegalArgumentException will be thrown. When sending a smaller amount of data, you can adjust the length to fit—you do not need to resize the data buffer. void setPort(int port)— assigns a new destination port to a DatagramPacket.
  • 8. DatagramSocket Class The DatagramSocket class provides access to a UDP socket, which allows UDP packets to be sent and received . A DatagramPacket is used to represent a UDP packet, and must be created prior to receiving any packets. The same DatagramSocket can be used to receive packets as well as to send them. However, read operations are blocking, meaning that the application will continue to wait until a packet arrives. A DatagramSocket can be used to both send and receive packets. Each DatagramSocket binds to a port on the local machine, which is used for addressing packets . The application is a UDP server , it will usually choose a specific port number . If the DatagramSocket is intended to be a client , and doesn't need to bind to a specific port number, a blank constructor can be specified .
  • 9. Creating a DatagramSocket To create a client DatagramSocket , the following constructor is used: DatagramSocket () throws java.net.SocketException . To create a server DatagramSocket , the following constructor is used, which takes as a parameter the port to which the UDP service will be bound: DatagramSocket(int port ) throws java.net.SocketException . Although rarely used, there is a third constructor for DatagramSocket . If a machine is known by several IP addresses, you can specify the IP address and port to which a UDP service should be bound. It takes as parameters the port to which the UDP service will be bound, as well as the InetAddress of the service. This constructor is: DatagramSocket ( int port , InetAddress addr ) throwsjava.net.SocketException . Port is Local !!!
  • 10. Using a DatagramSocket void close()— closes a socket, and unbinds it from the local port. void connect(InetAddress remote_addr int remote_port)— restricts access to the specified remote address and port. The designation is a misnomer, as UDP doesn't actually create a &quot;connection&quot; between one machine and another. void disconnect()— disconnects the DatagramSocket and removes any restrictions imposed on it by an earlier connect operation. !!! Sai InetAddress getInetAddress()— returns the remote address to which the socket is connected, or null if no such connection exists. int getPort ()— returns the remote port to which the socket is connected, or –1 if no such connection exists. InetAddress getLocalAddress()— returns the local address to which the socket is bound. int getLocalPort ()— returns the local port to which the socket is bound. int getReceiveBufferSize () throws java.net.SocketException— returns the maximum buffer size used for incoming UDP packets.
  • 11. Using a DatagramSocket int getSendBufferSize() throws java.net.SocketException— returns the maximum buffer size used for outgoing UDP packets. int getSoTimeout() throws java.net.SocketException— returns the value of the timeout socket option. By default, this value will be zero, indicating that blocking I/O will be used. void receive(DatagramPacket packet) throws java.io.IOException— reads a UDP packet and stores the contents in the specified packet. The address and port fields of the packet will be overwritten with the sender address and port fields, and the length field of the packet will contain the length of the original packet, which can be less than the size of the packet's byte-array. If a timeout value has been specified, a java.io.InterruptedIOException will be thrown if the time is exceeded. void send(DatagramPacket packet) throws java.io.IOException— sends a UDP packet, represented by the specified packet parameter.
  • 12. Using a DatagramSocket void setReceiveBufferSize(int length) throws java.net.SocketException— sets the maximum buffer size used for incoming UDP packets. Whether the specified length will be adhered to is dependent on the operating system. void setSendBufferSize(int length) throws java.net.SocketException— sets the maximum buffer size used for outgoing UDP packets. Whether the specified length will be adhered to is dependent on the operating system. void setSoTimeout(int duration) throws java.net.SocketException— sets the value of the timeout socket option. This value is the number of milliseconds a read operation will block before throwing a java.io.InterruptedIOException.
  • 13. Listening for UDP Packets UDP packets are received by a DatagramSocket and translated into a DatagramPacket object. When an application wishes to read UDP packets, it calls the DatagramSocket.receive method, which copies a UDP packet into the specified DatagramPacket. The contents of the DatagramPacket are processed, and the process is repeated as needed.
  • 14. Listening for UDP Packets DatagramPacket packet = new DatagramPacket ( new byte[256], 256 ); DatagramSocket socket = new DatagramSocket( 2000 ); boolean finished = false; while (! finished ){ socket.receive (packet); // process the packet } socket.close(); When processing the packet, the application must work directly with an array of bytes . If, however, your application is better suited to reading text, you can use classes from the Java I/O package to convert between a byte array and another type of stream or reader. By hooking a ByteArrayInputStream to the contents of a datagram and then to another type of InputStream or an InputStreamReader , you can access the contents of UDP packets relatively easily. Many developers prefer to use Java I/O streams to process data, using a DataInputStream or a BufferedReader to access the contents of byte arrays.
  • 15. Listening for UDP Packets ByteArrayInputStream bin = new ByteArrayInputStream( packet.getData() ); DataInputStream din = new DataInputStream (bin); // Read the contents of the UDP packet .......
  • 17. Sending UDP packets DatagramSocket socket = new DatagramSocket(); DatagramPacket packet = new DatagramPacket (new byte[256],256); packet.setAddress (InetAddress.getByName (someServer)); packet.setPort (2000); boolean finished = false; while !finished ){ // Write data to packet buffer ......... packet.setData(…..); packet.setLength(…); socket.send (packet); // Do something else, like read other packets, or check to // see if no more packets to send ......... } socket.close();
  • 18. UDP PacketReceiveDemo - Server The application starts by binding to a specific port, 2000. Applications offering a service generally bind to a specific port. When acting as a receiver, your application should choose a specific port number, so that a sender can send UDP packets to this port. Next, the application prepares a DatagramPacket for storing UDP packets, and creates a new buffer for storing packet data. // Create a datagram socket, bound to the specific port 2000 DatagramSocket socket = new DatagramSocket(2000); System.out.println (&quot;Bound to local port &quot; + socket.getLocalPort()); // Create a datagram packet, containing a maximum buffer of 256 bytes DatagramPacket packet = new DatagramPacket(new byte[256], 256);
  • 19. UDP PacketReceiveDemo - Server Now the application is ready to read a packet. The read operation is blocking, so until a packet arrives, the server will wait. When a packet is successfully delivered to the application, the addressing information for the packet is displayed so that it can be determined where it came from. // Receive a packet - remember by default this is a blocking // operation socket.receive(packet); // Display packet information InetAddress remote_addr = packet.getAddress(); System.out.println (&quot;Sent by : &quot; + remote_addr.getHostAddress() ); System.out.println (&quot;Send from: &quot; + packet.getPort());
  • 20. UDP PacketReceiveDemo - Server To provide easy access to the contents of the UDP packet, the application uses a ByteArrayInputStream a DataInputStream to read from the packet. Reading one character at a time, the program displays the contents of the packet and then finishes. // Display packet contents, by reading from byte array DataInputStream din = new DataInputStream(new ByteArrayInputStream(packet.getData())); // Display only up to the length of the original UDP packet for (int i = 0; i < packet.getLength()/2; i++) { System.out.print(din.readChar()); } socket.close(); }
  • 21. UDP PacketSendDemo - Client The application starts by binding a UDP socket to a local port, which will be used to send the data packet. Unlike the receiver demonstration, it doesn't matter which local port is being used. In fact, any free port is a candidate, and you may find that running the application several times will result in different port numbers. After binding to a port, the port number is displayed to demonstrate this. // Create a datagram socket, bound to any available local port DatagramSocket socket = new DatagramSocket(); System.out.println (&quot;Bound to local port &quot; + socket.getLocalPort()); Before sending any data, we need to create a DatagramPacket . First, a ByteArrayOutputStream is used to create a sequence of bytes. Once this is complete, the array of bytes is passed to the DatagramPacket constructor.
  • 22. UDP PacketSendDemo - Client // Create a message to send using a UDP packet ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); dout.writeChars(&quot;Greetings!&quot;); // Get the contents of our message as an array of bytes byte[] barray = bout.toByteArray(); // Create a datagram packet, containing our byte array DatagramPacket packet = new DatagramPacket(barray, barray.length); Now that the packet has some data, it needs to be correctly addressed. As with a postal message, if it lacks correct address information it cannot be delivered. We start by obtaining an InetAddress for the remote machine, and then display its IP address. This InetAddress is passed to the setAddress method of DatagramPacket , ensuring that it will arrive at the correct machine. However, we must go one step further and specify a port number. In this case, port 2000 is matched, as the receiver will be bound to that port.
  • 23. UDP PacketSendDemo - Client System.out.println (&quot;Looking up hostname &quot; + hostname ); // Lookup the specified hostname, and get an InetAddress InetAddress remote_addr = InetAddress.getByName(hostname); System.out.println (&quot;Hostname resolved as &quot; + remote_addr.getHostAddress()); // Address packet to sender packet.setAddress (remote_addr); // Set port number to 2000 packet.setPort (2000); // Send the packet - remember no guarantee of delivery socket.send(packet);