栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Netty: Udp服务器和客户端

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Netty: Udp服务器和客户端

1.引入相关依赖:



    4.0.0

    cn.edu.tju
    nettyudp
    1.0-SNAPSHOT
    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    8
                    8
                
            

        
    
    
        
        
            io.netty
            netty-all
            4.1.73.Final
        

        
        
            com.google.protobuf
            protobuf-java
            3.0.0
        




    




2.创建服务器端处理器类:

package cn.edu.tju;

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.concurrent.ThreadLocalRandom;


public class ServerHandler extends SimpleChannelInboundHandler {
    private String[] reward={"一等奖","二等奖","三等奖","四等奖","五等奖"};
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String req=msg.content().toString(CharsetUtil.UTF_8);
        System.out.println(req);
        int index=ThreadLocalRandom.current().nextInt(reward.length);
        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("message from server: "+reward[index], CharsetUtil.UTF_8),msg.sender()));
    }
}

3.创建服务器端主类:

package cn.edu.tju;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class UdpServer {
    private static int port=8866;
    public static void main(String[] args) {
        EventLoopGroup group=new NioEventLoopGroup();
        try{
            Bootstrap bootstrap=new Bootstrap();
            bootstrap.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST,false)
                    .handler(new ServerHandler());
            bootstrap.bind(port).sync().channel().closeFuture().await();
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }finally {
            group.shutdownGracefully();
        }
    }
}

4.创建客户端处理器类:

package cn.edu.tju;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

public class ClientHandler extends SimpleChannelInboundHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String str=msg.content().toString(CharsetUtil.UTF_8);
        System.out.println(str);
    }
}

5.创建客户端主类:

package cn.edu.tju;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
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 java.net.InetSocketAddress;

public class UdpClient {
    private static int port=8866;
    public static void main(String[] args) {
        EventLoopGroup group=new NioEventLoopGroup();
        try{
            Bootstrap b=new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST,true).handler(new ClientHandler());
            Channel ch=b.bind(0).sync().channel();
            ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("message from client: hello,world",CharsetUtil.UTF_8), new InetSocketAddress("255.255.255.255",port)));
            if(!ch.closeFuture().await(60000)){
                System.out.println("超时");
            }
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }finally {
            group.shutdownGracefully();
        }
    }
}

6.分别运行服务器端主类和客户端主类:
结果如下:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/732445.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号