Java DatagramSocket send Object to UDP server
import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class Main { public static void main(String[] args) { try {//from w w w . ja va 2 s . c om // Create a DatagramSocket DatagramSocket socket = new DatagramSocket(); // Create a Message object to be sent Message msg = new Message("Remainder", "Return my book on Monday"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(msg); byte[] out = baos.toByteArray(); // Muticast group where packet has to sent InetAddress group = InetAddress.getByName(args[0]); // Port the receiver listens on int port = 8379; // Create a DatagramPacket with buffer, address and port DatagramPacket packet = new DatagramPacket(out, out.length, group, port); // Send the packet now socket.send(packet); System.out.println("Sent an object"); } catch (Exception e) { e.printStackTrace(); } } } class Message implements java.io.Serializable { String subject, text; Message(String s, String t) { this.subject = s; this.text = t; } String getSubject() { return subject; } String getText() { return text; } }