package UDP_Socket; import java.net.*; import java.io.*; public class PacketReceiver { public static void main(String[] args) { try { // Create a datagram socket, bound to the specific port 9999 DatagramSocket socket = new DatagramSocket(9999); // Create a datagram packet, containing a maximum buffer of 256 bytes DatagramPacket packet = new DatagramPacket(new byte[256], 256); // Receive a packet - remember by default this is a blocking operation //socket.setSoTimeout(10000); socket.receive(packet); System.out.println("Packet received!"); // Display packet information InetAddress remote_addr = packet.getAddress(); System.out.println("Sent by host: " + remote_addr.getHostAddress()); System.out.println("Sent from port: " + packet.getPort()); // Display packet contents, by reading from byte array ByteArrayInputStream bin = new ByteArrayInputStream(packet.getData()); // Display only up to the length of the original UDP packet 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); } } }
package UDP_Socket; import java.net.*; import java.io.*; public class PacketSender { public static void main(String[] args) { try { // Hostname/IP address of the remote server String hostname = "localhost"; // Lookup the specified hostname, and get an InetAddress System.out.println("Looking up hostname " + hostname); InetAddress remote_addr = InetAddress.getByName(hostname); System.out.println("Hostname resolved as " + remote_addr.getHostAddress()); // Create a datagram socket, bound to any available local port DatagramSocket socket = new DatagramSocket(); // Create a message to send using a UDP packet ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintStream pout = new PrintStream(bout); pout.print("Greetings!"); // 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); // Set the destination address of the packet packet.setAddress(remote_addr); // Set port number to 9999 packet.setPort(9999); // Send the packet - remember no guarantee of delivery socket.send(packet); System.out.println("Packet sent!"); socket.close(); } catch (UnknownHostException uhe) { System.err.println("Can't find host " + uhe.getMessage()); } catch (IOException ioe) { System.err.println("Error - " + ioe); } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)