java.net.MulticastSocket Example--reference

In this example we are going to explain how to use MulticastSocket in Java, in order to enable a server to easily send information to multiple clients, which are all connected to the same port and address. We will describe the whole process, by creating both the server and the client, and guide you through the main concepts that need to be understood to create this type of applications.

1. MulticastSocket Server

We are going to use a DatagramSocket,  to enable the server to send packets of information to the client/clients. A datagram, by definition, is “an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed”. Essentially, we are opening a DatagramSocket in order to send DatagramPacket messages to the client. We are using the datagram classes (instead of standard sockets) because they allow us to broadcast information to multiple clients, that are all connected to aMulticastSocket.

Let’s see the code of the server:

MulticastSocketServer.java

01 import java.io.IOException;
02 import java.net.DatagramPacket;
03 import java.net.DatagramSocket;
04 import java.net.InetAddress;
05 import java.net.UnknownHostException;
06  
07 public class MulticastSocketServer {
08      
09     final static String INET_ADDR = "224.0.0.3";
10     final static int PORT = 8888;
11  
12     public static void main(String[] args) throws UnknownHostException, InterruptedException {
13         // Get the address that we are going to connect to.
14         InetAddress addr = InetAddress.getByName(INET_ADDR);
15       
16         // Open a new DatagramSocket, which will be used to send the data.
17         try (DatagramSocket serverSocket = new DatagramSocket()) {
18             for (int i = 0; i < 5; i++) {
19                 String msg = "Sent message no " + i;
20  
21                 // Create a packet that will contain the data
22                 // (in the form of bytes) and send it.
23                 DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
24                         msg.getBytes().length, addr, PORT);
25                 serverSocket.send(msgPacket);
26       
27                 System.out.println("Server sent packet with msg: " + msg);
28                 Thread.sleep(500);
29             }
30         catch (IOException ex) {
31             ex.printStackTrace();
32         }
33     }
34 }

One thing that we need to take into consideration here, is that there are specific addresses that allow us to use a MulticastSocket are limited, specifically in the range of 224.0.0.0 to 239.255.255.255. Some of them are reserved, like 224.0.0.0. The address that we are using, 224.0.0.3, can be used safely.

2. MulticastSocket Client

Regarding the client, we are going to move a little bit differently. We are going to create a client class, that will accept incoming messages from the server, and then we are going to duplicate this class. The point here is that by using the same code, we can connect to the server seamlessly, while having as many clients as we like.

Let’s see the code of the client:

MulticastSocketClient.java

01 import java.io.IOException;
02 import java.net.DatagramPacket;
03 import java.net.InetAddress;
04 import java.net.MulticastSocket;
05 import java.net.UnknownHostException;
06  
07 public class MulticastSocketClient {
08      
09     final static String INET_ADDR = "224.0.0.3";
10     final static int PORT = 8888;
11  
12     public static void main(String[] args) throws UnknownHostException {
13         // Get the address that we are going to connect to.
14         InetAddress address = InetAddress.getByName(INET_ADDR);
15          
16         // Create a buffer of bytes, which will be used to store
17         // the incoming bytes containing the information from the server.
18         // Since the message is small here, 256 bytes should be enough.
19         byte[] buf = new byte[256];
20          
21         // Create a new Multicast socket (that will allow other sockets/programs
22         // to join it as well.
23         try (MulticastSocket clientSocket = new MulticastSocket(PORT)){
24             //Joint the Multicast group.
25             clientSocket.joinGroup(address);
26       
27             while (true) {
28                 // Receive the information and print it.
29                 DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
30                 clientSocket.receive(msgPacket);
31  
32                 String msg = new String(buf, 0, buf.length);
33                 System.out.println("Socket 1 received msg: " + msg);
34             }
35         catch (IOException ex) {
36             ex.printStackTrace();
37         }
38     }
39 }

First, we start the client, which will keep waiting for incoming packets of information. As soon as we start the server, it will send the information packets and the client will receive them and print the information on the screen.

Server Output

1 Server sent packet with msg: Sent message no 0
2 Server sent packet with msg: Sent message no 1
3 Server sent packet with msg: Sent message no 2
4 Server sent packet with msg: Sent message no 3
5 Server sent packet with msg: Sent message no 4

Client Output

1 Socket 1 received msg: Sent message no 0
2 Socket 1 received msg: Sent message no 1
3 Socket 1 received msg: Sent message no 2
4 Socket 1 received msg: Sent message no 3
5 Socket 1 received msg: Sent message no 4

In order to use multiple clients, just create anew Java project and copy-paste the code of the client, but change the output to Socket 2instead of Socket 1. You will see that when the server runs, the messages will be sent to both clients, and both clients will print the same results (except for the socket number part). Take a look at this screenshot here. We are running the first client through eclipse, the second through the command line, and the server through the command line as well.

Running a server and 2 clients.

3. Download the project

This was an example of MulticastSocket usage in Java.

Download
You can download the full source code of this example here : MulticastSocketServerMulticastSocketClient

reference from:

http://examples.javacodegeeks.com/core-java/net/multicastsocket-net/java-net-multicastsocket-example/

时间: 2024-10-10 02:29:05

java.net.MulticastSocket Example--reference的相关文章

自己挖坑自己跳 之JsonMappingException: (was java.lang.NullPointerException) (through reference chain:)

在Web项目中,我们经常会设计一些与界面相对应的JavaBean作为Entity,而为了兼容前台传入的空值,有些字段我们会用包装类型而不是基本类型.可是往往我的Entity已经设计完成,很多时候我们会在原来的Entity基础上修改字段返回值类型,而不是删去重写.于是问题就来了,一些大意的同学仅仅把属性的基本类型(如long)改为包装类型(如Long),而并没有将setter/getter的类型一起修改. 这种情况会报错,而且报的错经常会让人摸不着头脑.下面列举了一种情况,是利用com.faste

java组播MulticastSocket

在单播模式中有服务器端和客户端之分,而组播模式与单播模式不同,每个端都是以路由器或交换机做为中转广播站,任意一端向路由器或交换机发送消息,路由或交换机负责发送其他节点,每个节点都是同等的.所以在编程模式上用同一个类表示即可--MulticastSocket. MulticastSocket属于jdk提供的类,类路径为java.net.MulticastSocket,利用此类可以很方便地实现组播功能,下面展示一个简单例子,两个节点之间通过组播传输消息. ①节点一,指定组播地址为228.0.0.4,

理解java reference

Java世界泰山北斗级大作<Thinking In Java>切入Java就提出“Everything is Object”.在Java这个充满Object的世界中,reference是一切谜题的根源,所有的故事都是从这里开始的. Reference是什么? 如果你和我一样在进入Java世界之前曾经浪迹于C/C++世界,就一定不会对指针陌生.谈到指针,往日种种不堪回首的经历一下子涌上心头,这里不是抱怨的地方,让我们暂时忘记指针的痛苦,回忆一下最初接触指针的甜蜜吧!还记得你看过的教科书中,如何讲

Java Reference &amp; ReferenceQueue一览

Overview The java.lang.ref package provides more flexible types of references than are otherwise available, permitting limited interaction between the application and the Java Virtual Machine (JVM) garbage collector. It is an important package, centr

java的Reference学习

java中Reference学习 谈到Reference想到了什么 Reference提供了一种与jvm gc交互的一种方式,提到Reference,脑中应该浮现一些名词,gc.ReferenceQueue.SoftReference.WeakReference.PhantomReference.FinalReference以及最常见的强引用.我认为当一个小白开始学习Reference的时候应该想一个问题,强引用不够好么,为什么我还需要弱引用.软引用等等这些东西. 为什么我们需要它们 应用程序经

Java 6 JVM参数选项大全(中文版)

原文来自: http://kenwublog.com/docs/java6-jvm-options-chinese-edition.htm 本文是基于最新的SUN官方文档Java SE 6 Hotspot VM Options 编写的译文.主要介绍JVM中的非稳态选项及其使用说明. 为了让读者明白每个选项的含义,作者在原文基础上补充了大量的资料.希望这份文档,对正在研究JVM参数的朋友有帮助! 非稳态选项使用说明 -XX:+<option> 启用选项 -XX:-<option> 不

java编译命令工具javac

Reads Java class and interface definitions and compiles them into bytecode and class files. Synopsis javac [ options ] [ sourcefiles ] [ classes] [ @argfiles ] Arguments can be in any order: options Command-line options. See Options. sourcefiles One

没有指针的java语言

一.java中引用(reference)实质就是指针 与C语言的指针比较: 1.引用是受控的安全的 2.空引用会被检查 java中不能够访问没有引用到的内存,这也是java的自动垃圾回收机制的基础之一 二.C语言中的指针在java中的体现 1.传地址------对象 引用类型:引用 基本类型:没有对应的 2.指正运算---指针 *(p+5) -----arg[5] 3.函数指针---接口.lambda表达式 4.指向节点的指针----对象的引用 5.使用JNI Java Native Inter

java语音聊天

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package n.audio.chart; import java.io.IOException; import java.net.Da