UDP Data Transfer using Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

UDP Data Transfer using Java

Share This
In the following program, we will demonstrate, how data can be transferred between client and server using Transport Layer Protocol - UDP. This code is self-explanatory. Hence, first, you will learn to develop server-side application. Then, you will learn to develop client side application.
We know that UDP is connectionless protocol, hence at the time of testing you may not get response from the server in many times.
PacketSendDemo.java
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException; public class PacketSendDemo { public static void main(String args[]) { int argc = args.length; if (argc != 1) { System.out.println("Syntax :"); System.out.println("java PacketSendDemo hostname"); return; } String hostname = args[0]; try { System.out.println("Binding to a local port"); DatagramSocket socket = new DatagramSocket(); System.out.println("Bound to local port " + socket.getLocalPort()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintStream pout = new PrintStream(bout); pout.print("Greetings!"); byte[] barray = bout.toByteArray(); DatagramPacket packet = new DatagramPacket(barray, barray.length); System.out.println("Looking up hostname " + hostname); InetAddress remote_addr = InetAddress.getByName(hostname); System.out.println("Hostname resolved as " + remote_addr.getHostAddress()); packet.setAddress(remote_addr); packet.setPort(2000); socket.send(packet); System.out.println("Packet sent!"); } catch (UnknownHostException uhe) { System.err.println("Can't find host " + hostname); } catch (IOException ioe) { System.err.println("Error - " + ioe); } } }

PacketReceiveDemo.java
import java.net.*; import java.io.*; public class PacketReceiveDemo { public static void main(String args[]) { try { System.out.println("Binding to local port 2000"); DatagramSocket socket = new DatagramSocket(2000); System.out.println("Bound to local port " + socket.getLocalPort()); DatagramPacket packet = new DatagramPacket(new byte[256], 256); socket.receive(packet); System.out.println("Packet received!"); InetAddress remote_addr = packet.getAddress(); System.out.println("Sent by : " + remote_addr.getHostAddress()); System.out.println("Sent from: " + packet.getPort()); ByteArrayInputStream bin = new ByteArrayInputStream(packet.getData()); for (int i = 0; i < packet.getLength(); i++) { int data = bin.read(); if (data == -1) break; else System.out.print((char) data); } socket.close(); } catch (IOException ioe) { System.err.println("Error - " + ioe); } } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.