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.    }}
 
 

				
时间: 2024-10-22 10:49:32

netty的Udp单播、组播、广播实例+Java的Udp单播、组播、广播实例的相关文章

JAVA实现UDP组播聊天程序

分类: Java 一.实验环境 编程语言:Java1.5(运行在JVM(Java Virsual Machine)) 开发工具:eclipce3.2 测试环境:局域网 二.实验目的 社会已经进入信息时代,网络技术在飞速发展.大量应用都依赖于从一个主机向多个主机或者从多个主机向多个主机发送同一信息的能力,在Internet上分布的数目可能达数十万台,这些都需要更高的带宽,并且大大超出了单播的能力.一种能最大限度地利用现有带宽的重要技术是IP组播. 三.组播聊天程序的实现: /** * 该程序实现了

SQL群集下安装多实例并启用AlwaysOn可用性组功能

SQL群集+安装新实例+启用AlwaysOn可用性组功能 主要内容 并行安装运行SQL server 的不同版本和实例 启用AlwaysOn可用性组功能 实验环境 并行安装SQL Server 2012 +SQL Server 2016 场景1:基于SQL Server 2012搭建了Cluster01-SQL群集.   hostname IP 实例名 端口 说明 AD dc1.contoso.com 192.168.136.150       SQL SQL1.contoso.com 192.

Linux 网络编程——原始套接字实例:发送 UDP 数据包

以太网报文格式: 详细的说明,请看<MAC 头部报文分析>. IP 报文格式: 详细的说明,请看<IP 数据报格式详解>. UDP 报文格式: 详细的说明,请看<UDP 数据报格式详解>. 校验和函数: /******************************************************* 功能: 校验和函数 参数: buf: 需要校验数据的首地址 nword: 需要校验数据长度的一半 返回值: 校验和 ********************

无废话Android之activity的生命周期、activity的启动模式、activity横竖屏切换的生命周期、开启新的activity获取他的返回值、利用广播实现ip拨号、短信接收广播、短信监听器(6)

1.activity的生命周期 这七个方法定义了Activity的完整生命周期.实现这些方法可以帮助我们监视其中的三个嵌套生命周期循环: (1)Activity的完整生命周期 自第一次调用onCreate()开始,直到调用onDestory()为止.Activity在onCreate()中设置所有“全局”状态以完成初始化. 而在onDestory()中释放所有系统资源.例如,如果Activity有一个线程在后台运行从网络下载数据,它会在onCreate()创建线程, 而在onDestory()销

java使用UDP

Java中通信可以使用的协议包括TCP协议和UDP协议 UDP协议概念 UDP协议的全称是用户数据报协议 ,在网络中它与TCP协议一样用于处理数据包,但它是一种无连接的协议.在OSI模型中,在第四层--传输层,处于IP协议的上一层.UDP有不提供数据包分组.组装和不能对数据包进行排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的. 综上所述:UDP不提供可靠地保证,保证数据准确按序到达目的地 为什么要使用UDP 在选择使用协议的时候,选择UDP必须要谨慎?在网络质量令人不十分满

Java TCP/UDP socket 编程流程总结

最近正好学习了一点用java socket编程的东西.感觉整体的流程虽然不是很繁琐,但是也值得好好总结一下. Socket Socket可以说是一种针对网络的抽象,应用通过它可以来针对网络读写数据.就像通过一个文件的file handler就可以都写数据到存储设备上一样.根据TCP协议和UDP协议的不同,在网络编程方面就有面向两个协议的不同socket,一个是面向字节流的一个是面向报文的. 对socket的本身组成倒是比较好理解.既然是应用通过socket通信,肯定就有一个服务器端和一个客户端.

【Java基础】Java多线程之线程组和线程池

在上一篇文章中,讲述了线程的基本概念和用法,这里将继续讲述线程组和线程池的一些东西. 线程组:java.lang.ThreadGroup 1. 线程组的介绍 线程组表示一个线程的集合.此外,线程组也可以包含其他线程组.线程组构成一棵树,在树中,除了初始线程组外,每个线程组都有一个父线程组.允许线程访问有关自己的线程组的信息,但是不允许它访问有关其线程组的父线程组或其他任何线程组的信息.   2. 线程组的构造方法 ThreadGroup(String name) 构造一个新线程组. Thread

[java]基于UDP的Socket通信Demo

java课编程作业:在老师给的demo的基础上实现客户端发送数据到服务器端,服务器端接受客户端后进行数据广播. 整体功能类似于聊天室,代码部分不是太难,但是在本机测试的时候出现这样的问题: 服务端通过将每一个Socket客户端的IP存入Set集合,每次接受到数据后都向当前所有的IP转发.但是本机演示的时候所有开的ChatClient客户端都是同一IP,怎么测试呢? 解决办法就是本机测试时候服务端向多个不同的端口转发就好了,这样跑起来的客户端是在不同端口上进行监听的(只是为了实现广播,实际应用下还

【练习】增加日志组数至4组,且每组日志成员大小为50M,每组2个成员。

1.查看日志组成员路径及日志组大小.状态 SQL> select group#,member from v$logfile; GROUP# MEMBER ---------- -------------------------------------------------- 3 /u01/app/oracle/oradata/ORA11GR2/redo03.log 2 /u01/app/oracle/oradata/ORA11GR2/redo02.log 1 /u01/app/oracle/o