5.5. Sending UDP packets

The same interface (DatagramSocket) employed to receive UDP packets is also used to send them. When sending a packet, the application must create a DatagramPacket, set the address and port information, and write the data intended for transmission to its byte array. If replying to a received packet, the address and port information will already be stored, and only the data need be overwritten. Once the packet is ready for transmission, the send method of DatagramSocket is invoked, and a UDP packet is sent (see Figure 5-5).

Figure 5-5. Packets are sent using a DatagramSocket.

The following code snippet illustrates this process: ...

Get Java™ Network Programming and Distributed Computing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.