netty的Udp单播、组播、广播实例+Java的Udp单播、组播、广播实例
网络上缺乏netty的udp的单播、组播案例,经过一番学习总结之后终于把这两个案例调通,下面把这两个案例的代码放在这里分享一下。
首先推荐博文:
http://colobu.com/2014/10/21/udp-and-unicast-multicast-broadcast-anycast/#Netty%E4%B8%8E%E5%8D%95%E6%92%AD%EF%BC%8C%E7%BB%84%E6%92%AD
netty的Udp单播、组播、广播实例+Java的Udp单播、组播、广播实例,
这些代码实例可以直接到我的GitHub地址下载(https://github.com/Jethu1/netty_practice.git)。
1.单播的案例(包括TheMomentClient+TheMomentClientHandler+TheMomentServer+TheMomentServerHandler+SoketUtils五个类)
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import practice13_UdpBroadcast.SocketUtils; /**
* A UDP broadcast client that asks for a quote of the moment (QOTM) to {@link TheMomentServer}.
*
* Inspired by <a href="http://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html">the official
* Java tutorial</a>.
*/
public final class TheMomentClient { static final int PORT = Integer.parseInt(System.getProperty("port", "7686")); public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.remoteAddress("127.0.0.1",PORT)
.handler(new TheMomentClientHandler()); Channel ch = b.bind(0).sync().channel(); // Broadcast the QOTM request to port 8080.
ch.writeAndFlush(new DatagramPacket(
Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
SocketUtils.socketAddress("127.0.0.1", PORT))).sync(); // TheMomentClientHandler will close the DatagramChannel when a
// response is received. If the channel is not closed within 5 seconds,
// print an error message and quit.
if (!ch.closeFuture().await(5000)) {
System.err.println("QOTM request timed out.");
}
} finally {
group.shutdownGracefully();
}
}
}
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package practice14_Udp_Unicast; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil; public class TheMomentClientHandler extends SimpleChannelInboundHandler<DatagramPacket> { @Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
String response = msg.content().toString(CharsetUtil.UTF_8);
if (response.startsWith("QOTM: ")) {
System.out.println("Quote of the Moment: " + response.substring(6));
ctx.close();
}
System.out.println("client receive message from the server");
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package practice14_Udp_Unicast; import io.netty.bootstrap.Bootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel; /**
* A UDP server that responds to the QOTM (quote of the moment) request to a {@link TheMomentClient}.
*
* Inspired by <a href="http://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html">the official
* Java tutorial</a>.
*/
public final class TheMomentServer { private static final int PORT = Integer.parseInt(System.getProperty("port", "7686")); public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.localAddress(PORT)
.handler(new TheMomentServerHandler()); b.bind(PORT).sync().channel().closeFuture().await();
} finally {
group.shutdownGracefully();
}
}
}
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package practice14_Udp_Unicast; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil; import java.util.Random; public class TheMomentServerHandler extends SimpleChannelInboundHandler<DatagramPacket> { private static final Random random = new Random(); // Quotes from Mohandas K. Gandhi:
private static final String[] quotes = {
"Where there is love there is life.",
"First they ignore you, then they laugh at you, then they fight you, then you win.",
"Be the change you want to see in the world.",
"The weak can never forgive. Forgiveness is the attribute of the strong.",
}; private static String nextQuote() {
int quoteId;
synchronized (random) {
quoteId = random.nextInt(quotes.length);
}
return quotes[quoteId];
} @Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
System.err.println(packet);
System.out.println("I receive your message");
if ("QOTM?".equals(packet.content().toString(CharsetUtil.UTF_8))) {
ctx.write(new DatagramPacket(
Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8), packet.sender()));
}
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
// We don't close the channel because we can keep serving requests.
}
}
import io.netty.util.internal.PlatformDependent; import java.io.IOException;
import java.net.*;
import java.nio.channels.DatagramChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Enumeration;
public final class SocketUtils { private SocketUtils() {
} public static void connect(final Socket socket, final SocketAddress remoteAddress, final int timeout)
throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() { public Void run() throws IOException {
socket.connect(remoteAddress, timeout);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
} public static void bind(final Socket socket, final SocketAddress bindpoint) throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() { public Void run() throws IOException {
socket.bind(bindpoint);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
} public static boolean connect(final SocketChannel socketChannel, final SocketAddress remoteAddress)
throws IOException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() { public Boolean run() throws IOException {
return socketChannel.connect(remoteAddress);
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
} public static SocketChannel accept(final ServerSocketChannel serverSocketChannel) throws IOException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<SocketChannel>() { public SocketChannel run() throws IOException {
return serverSocketChannel.accept();
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
} /* public static void bind(final DatagramChannel networkChannel, final SocketAddress address) throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
networkChannel.bind(address);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}*/ public static SocketAddress localSocketAddress(final ServerSocket socket) {
return AccessController.doPrivileged(new PrivilegedAction<SocketAddress>() { public SocketAddress run() {
return socket.getLocalSocketAddress();
}
});
} public static InetAddress addressByName(final String hostname) throws UnknownHostException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<InetAddress>() { public InetAddress run() throws UnknownHostException {
return InetAddress.getByName(hostname);
}
});
} catch (PrivilegedActionException e) {
throw (UnknownHostException) e.getCause();
}
} public static InetAddress[] allAddressesByName(final String hostname) throws UnknownHostException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<InetAddress[]>() { public InetAddress[] run() throws UnknownHostException {
return InetAddress.getAllByName(hostname);
}
});
} catch (PrivilegedActionException e) {
throw (UnknownHostException) e.getCause();
}
} public static InetSocketAddress socketAddress(final String hostname, final int port) {
return AccessController.doPrivileged(new PrivilegedAction<InetSocketAddress>() { public InetSocketAddress run() {
return new InetSocketAddress(hostname, port);
}
});
} public static Enumeration<InetAddress> addressesFromNetworkInterface(final NetworkInterface intf) {
return AccessController.doPrivileged(new PrivilegedAction<Enumeration<InetAddress>>() { public Enumeration<InetAddress> run() {
return intf.getInetAddresses();
}
});
} /* public static InetAddress loopbackAddress() {
return AccessController.doPrivileged(new PrivilegedAction<InetAddress>() {
@Override
public InetAddress run() {
if (PlatformDependent.javaVersion() >= 7) {
return InetAddress.getLoopbackAddress();
}
try {
return InetAddress.getByName(null);
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
}
});
}*/ /* public static byte[] hardwareAddressFromNetworkInterface(final NetworkInterface intf) throws SocketException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<byte[]>() { public byte[] run() throws SocketException {
return intf.getHardwareAddress();
}
});
} catch (PrivilegedActionException e) {
throw (SocketException) e.getCause();
}
}
*/
} 2.netty udp组播的案例(包括MulticastClient+MulticastClientHandler+MultcastServer+MultcastServerHandler+SoketUtils五个类)
package practice12_Udp_Multicast; /**
* Created by jet on 2017/6/14.
*/
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ChannelFactory;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.InternetProtocolFamily;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.NetUtil; import java.net.*;
import java.util.Enumeration; public class MulticastClient extends Thread {
private InetSocketAddress groupAddress; public MulticastClient(InetSocketAddress groupAddress) {
this.groupAddress = groupAddress;
}
public void run() {
EventLoopGroup group = new NioEventLoopGroup();
try {
// NetworkInterface ni = NetworkInterface.getByName("en1");
NetworkInterface ni = NetUtil.LOOPBACK_IF;
Enumeration<InetAddress> addresses = ni.getInetAddresses();
InetAddress localAddress = null;
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (address instanceof Inet4Address){
localAddress = address;
}
} Bootstrap b = new Bootstrap();
b.group(group)
.channelFactory(new ChannelFactory<NioDatagramChannel>() { public NioDatagramChannel newChannel() {
return new NioDatagramChannel(InternetProtocolFamily.IPv4);
}
})
.localAddress(localAddress, groupAddress.getPort())
.option(ChannelOption.IP_MULTICAST_IF, ni)
.option(ChannelOption.SO_REUSEADDR, true)
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
public void initChannel(NioDatagramChannel ch) throws Exception {
ch.pipeline().addLast(new ClientMulticastHandler());
}
}); Channel ch = b.bind().sync().channel();
ch.writeAndFlush(new DatagramPacket(
Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
groupAddress)).sync(); ch.close().awaitUninterruptibly();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
} public static void main(String[] args) throws Exception {
InetSocketAddress groupAddress = new InetSocketAddress("239.255.27.1", 1234);
new MulticastClient(groupAddress).run();
}
}
package practice12_Udp_Multicast; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil; /**
* Created by jet on 2017/6/14.
*/
public class ClientMulticastHandler extends SimpleChannelInboundHandler<DatagramPacket> { @Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
String response = msg.content().toString(CharsetUtil.UTF_8);
System.out.println("client receive message from server");
if (response.startsWith("QOTM: ")) {
System.out.println("Quote of the Moment: " + response.substring(6));
ctx.close();
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
package practice12_Udp_Multicast; /**
* Created by jet on 2017/6/14.
*/
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ChannelFactory;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.InternetProtocolFamily;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.NetUtil; import java.net.*;
import java.util.Enumeration; public class MulticastServer extends Thread {
private InetSocketAddress groupAddress; public MulticastServer(InetSocketAddress groupAddress) {
this.groupAddress = groupAddress;
} public void run() {
EventLoopGroup group = new NioEventLoopGroup();
try {
// NetworkInterface ni = NetworkInterface.getByName("en1");
NetworkInterface ni = NetUtil.LOOPBACK_IF;
Enumeration<InetAddress> addresses = ni.getInetAddresses();
InetAddress localAddress = null;
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (address instanceof Inet4Address){
localAddress = address;
}
} Bootstrap b = new Bootstrap();
b.group(group)
.channelFactory(new ChannelFactory<NioDatagramChannel>() { public NioDatagramChannel newChannel() {
return new NioDatagramChannel(InternetProtocolFamily.IPv4);
}
})
.localAddress(localAddress, groupAddress.getPort())
.option(ChannelOption.IP_MULTICAST_IF, ni)
.option(ChannelOption.SO_REUSEADDR, true)
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
public void initChannel(NioDatagramChannel ch) throws Exception {
ch.pipeline().addLast(new ServerMulticastHandler());
}
}); NioDatagramChannel ch = (NioDatagramChannel)b.bind(groupAddress.getPort()).sync().channel();
ch.joinGroup(groupAddress, ni).sync();
System.out.println("server"); ch.closeFuture().await(); } catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
} public static void main(String[] args) throws Exception {
InetSocketAddress groupAddress = new InetSocketAddress("239.255.27.1", 1234);
new MulticastServer(groupAddress).run();
}
}
package practice12_Udp_Multicast; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil; import java.util.Random; /**
* Created by jet on 2017/6/14.
*/
public class ServerMulticastHandler extends SimpleChannelInboundHandler<DatagramPacket> {
private static final Random random = new Random(); // Quotes from Mohandas K. Gandhi:
private static final String[] quotes = {
"Where there is love there is life.",
"First they ignore you, then they laugh at you, then they fight you, then you win.",
"Be the change you want to see in the world.",
"The weak can never forgive. Forgiveness is the attribute of the strong.",
}; private static String nextQuote() {
int quoteId;
synchronized (random) {
quoteId = random.nextInt(quotes.length);
}
return quotes[quoteId];
} @Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
System.err.println(packet);
System.out.println("The server receive message from client");
if ("QOTM?".equals(packet.content().toString(CharsetUtil.UTF_8))) {
System.out.println("the server write some info to client");
ctx.write(new DatagramPacket(
Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8), packet.sender()));
}
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
// We don't close the channel because we can keep serving requests.
}
}
netty的Udp单播、组播、广播实例+Java的Udp单播、组播、广播实例的更多相关文章
- c++ 网络编程(六)LINUX下 socket编程 多播与广播 实现一次发送所有组客户端都能接收到
原文作者:aircraft 原文链接:https://www.cnblogs.com/DOMLX/p/9614288.html 一.多播 锲子:有这么一种情况,网络电台可能需要同时向成千上万的用户传输 ...
- Bootstrap历练实例:默认的列表组
Bootstrap 列表组 本章我们将讲解列表组.列表组件用于以列表形式呈现复杂的和自定义的内容.创建一个基本的列表组的步骤如下: 向元素 <ul> 添加 class .list-grou ...
- bootstrap历练实例:按钮作为输入框组前缀或后缀
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...
- Bootstrap历练实例:垂直的按钮组
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...
- [源码分析] 从实例和源码入手看 Flink 之广播 Broadcast
[源码分析] 从实例和源码入手看 Flink 之广播 Broadcast 0x00 摘要 本文将通过源码分析和实例讲解,带领大家熟悉Flink的广播变量机制. 0x01 业务需求 1. 场景需求 对黑 ...
- 从UDP的”连接性”说起–告知你不为人知的UDP
原文地址:http://bbs.utest.qq.com/?p=631 很早就计划写篇关于UDP的文章,尽管UDP协议远没TCP协议那么庞大.复杂,但是,要想将UDP描述清楚,用好UDP却要比TCP难 ...
- 无废话Android之activity的生命周期、activity的启动模式、activity横竖屏切换的生命周期、开启新的activity获取他的返回值、利用广播实现ip拨号、短信接收广播、短信监听器(6)
1.activity的生命周期 这七个方法定义了Activity的完整生命周期.实现这些方法可以帮助我们监视其中的三个嵌套生命周期循环: (1)Activity的完整生命周期 自第一次调用onCrea ...
- 【练习】增加日志组数至4组,且每组日志成员大小为50M,每组2个成员。
1.查看日志组成员路径及日志组大小.状态 SQL> select group#,member from v$logfile; GROUP# MEMBER ---------- --------- ...
- 【Java基础】Java多线程之线程组和线程池
在上一篇文章中,讲述了线程的基本概念和用法,这里将继续讲述线程组和线程池的一些东西. 线程组:java.lang.ThreadGroup 1. 线程组的介绍 线程组表示一个线程的集合.此外,线程组也可 ...
随机推荐
- xssbypass小记
简单整理下bypass的一些点 标签外 如果是标签之外 又有htmlspecialchars函数的点 就别想了 在标签外同时能xss但是有长度限制 如果是储存型可以利用多个点 然后构造<scri ...
- Ubuntu无法安装vim怎么办?(Ubuntu 出现apt-get: Package has no installation candidate问题)
apt-get install vim 正在读取软件包列表... 完成 正在分析软件包的依赖关系树 正在读取状态信息... 完成 有一些软件包无法被安装.如果您用的是不稳定(unstable)发行版, ...
- Python的类(二)
一.类的重写 对于父类的方法,只要它不符合子类模拟的实物的行为,都可对其进行重写.为此,可在子类中定义一个这样的方法,即它与要重写的父类方法同名.这样, Python将不会考虑这个父类方法,而只关注你 ...
- n个台阶,每次都可以走一步,走两步,走三步,走到顶部一共有多少种可能
分析 第一个台阶 1第二个台阶 11 2 //走两次1步或者走1次两步第三个台阶 111 12 21 3 第四个台阶 1111 112 121 211 22 13 31 思想:4阶台阶, ...
- 【jQuery】 常用函数
[jQuery] 常用函数 html() : 获取设置元素内的 html,包含标签 text() : 获取设置元素内的文本, 不包含标签 val() : 获取设置 value 值 attr() : 获 ...
- Unity 3d C#和Javascript脚本互相调用 解决方案(非原创、整理资料,并经过实践得来)
Unity 3d C#和Javascript脚本互相调用 解决方案 1.背景知识 脚本的编译过程分四步: 1. 编译所有 ”Standard Assets”, “Pro Standard Assets ...
- 虚拟现实-VR-UE4-获取UE4
UE4现在虽然是开源,但是并不是免费的,在你的游戏成功后,回收取5%费用和每个月19美元的费用 所以,第一步,进去UE4官网:https://www.unrealengine.com/zh-CN/wh ...
- Python 基本文件操作
文件模式 'r' 读模式 'w' 写模式 (清除掉旧有数据并重新开始) 'a' 追加模式 'b' 二进制模式 '+' 读/写模式 注意: 'b' : 二进制模式 可添加到其他模式中使用 '+' ...
- 1030 Travel Plan (30 分)(最短路径 and dfs)
#include<bits/stdc++.h> using namespace std; ; const int inf=0x3f3f3f3f; int mp[N][N]; bool vi ...
- ipfs01
IPFS音乐播放器 IPFS相关 IPFS第一次亲密接触 什么是IPFS IPFS对比HTTP/FTP等协议的优势 IPFS应用场景 ipfs入门 官网地址:https://ipfs.io 下载安 ...