Netty实现UDP

最近写的tcp和udp

以前经常写tcp,这次突然多一个udp。

这次就献上udpserver的代码

 

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;
 
/**
 * 19.2.15
 */
public class UdpServer {
	public static void main(String[] args) {
	    try {
	        Bootstrap b = new Bootstrap();
	        EventLoopGroup group = new NioEventLoopGroup();
	        b.group(group)
	                .channel(NioDatagramChannel.class)
	                .option(ChannelOption.SO_BROADCAST, true)
	                .handler(new UdpServerHandler());

	        b.bind(2557).sync().channel().closeFuture().await();
	    } catch (InterruptedException e) {
	        e.printStackTrace();
	    }
	}
}

 

import com.wlzl.wq.util.Effect;
import com.wlzl.wq.util.HexByte;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
		//做类型转换,将msg转换成Netty的ByteBuf对象。
		//ByteBuf类似于JDK中的java.nio.ByteBuffer 对象,不过它提供了更加强大和灵活的功能。
		ByteBuf buf = packet.copy().content();

		//通过ByteBuf的readableBytes方法可以获取缓冲区可读的字节数,
		//根据可读的字节数创建byte数组
		byte[] req = new byte[buf.readableBytes()];
		//通过ByteBuf的readBytes方法将缓冲区中的字节数组复制到新建的byte数组中
		buf.readBytes(req);
		//通过new String构造函数获取请求消息。
		String body = HexStringUtils.bytesToHexString(req).toUpperCase();
		System.out.println(body);//打印收到的信息
			//向客户端发送消息
	        String json = "hello world!!";
	        // 由于数据报的数据是以字符数组传的形式存储的,所以传转数据
	        byte[] bytes = json.getBytes("UTF-8");
	        DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(bytes), packet.sender());
	        ctx.writeAndFlush(data);//向客户端发送消息
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值