JavaQuick Tip: Java Multicast Sockets

Quick Tip: Java Multicast Sockets

Java Developer Tutorials

The code below shows developers how to use the java.net.MulticastSocket, add them to a group, and used them to publish data in Java:

*/

import java.net.InetAddress;
import java.net.MulticastSocket;

public class SocketJoinGroup
{
	public static void main(String args[])
	{
		SocketJoinGroup socketJoinGroup = new SocketJoinGroup();
		socketJoinGroup.proceed();
	}
	
	private void proceed()
	{
		try
		{
			String ipAddressForGroup = "226.3.4.5";
			InetAddress group = InetAddress.getByName(ipAddressForGroup);
			MulticastSocket multicastSocket = new MulticastSocket(7654);
			multicastSocket.joinGroup(group);
			System.out.println("Joined group: " + group);
		}
		catch(Exception exception)
		{
			System.out.println("Exception: " + exception);
		}
	}
}

/*

Note that your output might be different based on the Java development environment that you are using:

 
[root@mypc]# java SocketJoinGroup
Joined group: /226.3.4.5

Read more Java programming tutorials.

Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.
Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.

Latest Posts

Related Stories