Netty UDP Server&Client

 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() {
                @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 {
    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();
        }
    }
}

 

你可能感兴趣的:(MAC&iPhone开发,Java,Android,架构)