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; |
07 |
public class MulticastSocketServer { |
09 |
final static String INET_ADDR = "224.0.0.3" ; |
10 |
final static int PORT = 8888 ; |
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); |
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; |
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); |
27 |
System.out.println( "Server sent packet with msg: " + msg); |
30 |
} catch (IOException ex) { |
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; |
07 |
public class MulticastSocketClient { |
09 |
final static String INET_ADDR = "224.0.0.3" ; |
10 |
final static int PORT = 8888 ; |
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); |
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 ]; |
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); |
28 |
// Receive the information and print it. |
29 |
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length); |
30 |
clientSocket.receive(msgPacket); |
32 |
String msg = new String(buf, 0 , buf.length); |
33 |
System.out.println( "Socket 1 received msg: " + msg); |
35 |
} catch (IOException ex) { |
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.
reference from:
http://examples.javacodegeeks.com/core-java/net/multicastsocket-net/java-net-multicastsocket-example/
- 自己挖坑自己跳 之JsonMappingException: (was java.lang.NullPointerException) (through reference chain:)
在Web项目中,我们经常会设计一些与界面相对应的JavaBean作为Entity,而为了兼容前台传入的空值,有些字段我们会用包装类型而不是基本类型.可是往往我的Entity已经设计完成,很多时候我们会 ...
- Java中各种引用(Reference)解析
目录 1,引用类型 2, FinalReference 2.1, Finalizer 3, SoftReference 4, WeakReference 5, PhantomReference 6, ...
- Java密码体系结构简介:Java Cryptography Architecture (JCA) Reference Guide
来自Java官方的文档,作备忘使用. 简介: Java平台非常强调安全性,包括语言安全,密码学,公钥基础设施,认证,安全通信和访问控制. JCA是平台的一个主要部分,包含一个“提供者”体系结构和一组用 ...
- java 方法引用(method reference)
it -> it != null等价于Objects::nonNull
- java之DatagramSocket、DatagramPackage丶MulticastSocket 广播学习
1.基本概念: a.DatagramPacket与DatagramSocket位于java.net包中 b.DatagramPacket表示存放数据的数据报,DatagramSocket表示接受或发送 ...
- 理解java reference
Java世界泰山北斗级大作<Thinking In Java>切入Java就提出“Everything is Object”.在Java这个充满Object的世界中,reference是一 ...
- java组播MulticastSocket
在单播模式中有服务器端和客户端之分,而组播模式与单播模式不同,每个端都是以路由器或交换机做为中转广播站,任意一端向路由器或交换机发送消息,路由或交换机负责发送其他节点,每个节点都是同等的.所以在编程模 ...
- Java基本功—Reference
这是一篇一年多之前便已写就的文章,那时,因为很多Java程序员只求追随新生的事物,却连基本的概念都没有,很多讨论中,很明显是基本功不过硬,于是萌生写一个系列文章,讨论Java的基本功,下面便是在这个想 ...
- Java Reference & ReferenceQueue一览
Overview The java.lang.ref package provides more flexible types of references than are otherwise ava ...
随机推荐
- 33.Spring整合Struts2.md
[toc] 1.搭建环境 在idea下可以在创建module时候选择,注意WEB-INF下的classes和lib两个目录需要手动创建,并且对应的配置文件和依赖的lib需要手动拷贝到这两个文件夹下 2 ...
- 【转】K短路
K短路 用dijsktra+A*启发式搜索 当点v第K次出堆的时候,这时候求得的路径是k短路.A*算法有一个启发式函数f(p)=g(p)+h(p), 即评估函数=当前值+当前位置到终点的最短距离g(p ...
- js 判断url的?后参数是否包含某个字符串
function GetQueryString(name){ var reg=eval("/"+name+"/g"); var r = window. ...
- .ctor,.cctor 以及 对象的构造过程
摘要: .ctor,.cctor 以及 对象的构造过程.ctor:简述:构造函数,在类被实例化时,它会被自动调用.当C#的类被编译后,在IL代码中会出现一个名为.ctor的方法,它就是我们的构造函数, ...
- BAT清理垃圾
@echo off title ϵͳȥm del /f /s /q %systemdrive%\*.tmp del /f /s /q %systemdrive%\*._mp del /f /s /q ...
- win7 IIS7.0 【IIS 管理器无法验证此内置帐户是否有访问权】
异常信息: 服务器配置为将传递身份验证和内置帐户一起使用,以访问指定的物理路径.但是,IIS 管理器无法验证此内置帐户是否有访问权.请确保应用程序池标识具有该物理路径的读取访问权.如果此服务器加入到域 ...
- TCP回射服务器程序:main函数
TCP回射并发服务器 1.创建套接字,绑定服务器的众所周知端口 创建一个TCP套接字,在待绑定到该TCP套接字的网际网套接字地址结构中填入通配地址(INADDR_ANY) 和服务器的众所知周(SERV ...
- 转:NoSQL更适合担当云数据库吗
在过去几十年,关系型数据库管理系统一直是数据管理的主要模型,随着Web应用数据规模的显著增长,NoSQL系统逐渐引起关注.领域专家Sherif Sakr分析指出,NoSQL具备的优势(能够水平扩展数据 ...
- Milking Grid
poj2185:http://poj.org/problem?id=2185 题意:在一个字符矩阵中,找一个最小的字符子矩阵,使其能够覆盖整个矩阵. 题解:在KMP中i-next[i]是这能够覆盖这个 ...
- Cracking the coding interview--Q2.4
Write code to partition a linked list around a value x, such that all nodes less than xcome before a ...