Netty UDP Server&Client

18 篇文章 0 订阅
13 篇文章 1 订阅

 UDP Server:

package cn.insighters.udp;

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

import java.net.InetAddress;

/**
 * Discards any incoming data.
 */
public class UdpServer {

    private int port;

    public UdpServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        final NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            final Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                @Override
                public void initChannel(final NioDatagramChannel ch) throws Exception {

                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new IncomingPacketHandler());
                }
            });

            // Bind and start to accept incoming connections.
            InetAddress address  = InetAddress.getLocalHost();
            b.bind(address,port).sync().channel().closeFuture().await();

        } finally {
        System.out.print("In Server Finally");
        }
    }

    public static void main(String[] args) throws Exception {
        final int port = 9956;
        new Thread(new Runnable() {

			@Override
			public void run() {
				 try {
					new UdpServer(port).run();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
        	
        }).start();
       
        for(int i = 0; i < 10; i++) {
        	UdpClient.send("192.168.1.30", port, "" + i + ": " + "{\"command\":\"heartbeat_resp\",\"status\":\"一切正常\"}");
        	try {
        		Thread.sleep(1000);
        	}catch(Exception e) {
        		
        	}
        }
        
    }
}

 

UDP Server Handler:

package cn.insighters.udp;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;


import java.net.InetAddress;

public class IncomingPacketHandler extends  SimpleChannelInboundHandler<DatagramPacket> {
    IncomingPacketHandler(){
    }
	@Override
	protected void channelRead0(ChannelHandlerContext arg0, DatagramPacket packet) throws Exception {
        final InetAddress srcAddr = packet.sender().getAddress();
        final int port = packet.sender().getPort();
        final ByteBuf buf = packet.content();
        final int rcvPktLength = buf.readableBytes();
        final byte[] rcvPktBuf = new byte[rcvPktLength];
        buf.readBytes(rcvPktBuf);
        System.out.println("从" + srcAddr.toString() + ":" + port + "收到数据:" + new String(rcvPktBuf));
	}
}

UDP Client:

package cn.insighters.udp;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UdpClient {
    public static void send(String ip, int port, String content){
        byte[] buf = new byte[256];
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress address = null;
		try {
			address = InetAddress.getByName(ip);
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        try {
			buf= content.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, port);
        try {
            socket.send(packet);
            System.out.println("发送:" + new String(buf));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值