我就不多说了,参考 百度百科
跟我个人理解,需要注意的是:
1、UDP的有效端口范围在0-65535之间,大约49151的端口都代表动态端口
2、UDP是一种无连接的,不可靠的传输层协议
接下来就是Netty实现UDP,
他简化网络应用的编程过程开发,例如UDP和TCP的socket服务开发,他功能比较强大,并且提供了编码好解码的能力,并且很多著名的框架都是底层采用Netty,比如Dubbo,服务提供者和消费者之间的通信。淘宝的消息中间件 RocketMQ 的消息生产者和消息消费者之间
大致结构:
1.所需的netty的jar
io.netty
netty-all
4.1.49.Final
2.ThreeUdpServer
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
/**
* 说 明:UdpServer
*/
public class ThreeUdpServer {
private final Bootstrap bootstrap;
private final NioEventLoopGroup acceptGroup;
private Channel channel;
public void start(String host,int port) throws Exception{
try {
channel = bootstrap.bind(host, port).sync().channel();
System.out.println("ThreeUdpServerHandler start success"+port);
channel.closeFuture().await();
} finally {
acceptGroup.shutdownGracefully();
}
}
public Channel getChannel(){
return channel;
}
public static ThreeUdpServer getInstance(){
return UdpServerHolder.INSTANCE;
}
private static final class UdpServerHolder{
static final ThreeUdpServer INSTANCE = new ThreeUdpServer();
}
private ThreeUdpServer(){
bootstrap = new Bootstrap();
acceptGroup = new NioEventLoopGroup();
bootstrap.group(acceptGroup)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new ChannelInitializer() {
@Override
protected void initChannel(NioDatagramChannel ch)
throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ThreeUdpServerHandler());
}
});
}
}
3.ThreeUdpServerHandler
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;
import lombok.extern.slf4j.Slf4j;
/**
* 说 明:
*
*/
@Slf4j
public class ThreeUdpServerHandler extends SimpleChannelInboundHandler{
// @Override
// public void channelActive(ChannelHandlerContext ctx) throws Exception {
// //当channel就绪后。
// Channel incoming = ctx.channel();
// System.out.println("UDP-Client:" + incoming.remoteAddress() + "上线");
// }
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg)
throws Exception {
// 接受client的消息
log.info("开始接收来自client的数据");
final ByteBuf buf = msg.content();
int readableBytes = buf.readableBytes();
byte[] content = new byte[readableBytes];
buf.readBytes(content);
String clientMessage = new String(content,"UTF-8");
log.info("Read clientMessage is: "+clientMessage);
if(clientMessage.contains("UdpServer")){
ctx.writeAndFlush(new DatagramPacket(Unpooled.wrappedBuffer("helloClient".getBytes()),msg.sender())).sync();
}
}
//捕获异常
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.error("UdpServerHandler exceptionCaught" + cause.getMessage());
cause.printStackTrace();
ctx.close();
}
}
4.ThreeUdpServerTest
public class ThreeUdpServerTest {
private static final String host = "192.168.1.184";
private static final int port = 60000;
public static void main(String[] args) {
try {
ThreeUdpServer.getInstance().start(host, port);
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.ThreeUdpClient
import com.zxk.netty.udp.three.decode.ThreeUdpClientDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.tomcat.jni.Local;
import java.nio.charset.Charset;
/**
* 说 明:LogPush UDP client
*/
public class ThreeUdpClient {
private final Bootstrap bootstrap;
public final NioEventLoopGroup workerGroup;
public static Channel channel;
private static final Charset ASCII = Charset.forName("ASCII");
public void start(Integer localPort) throws Exception{
try {
channel = bootstrap.bind(localPort).sync().channel();
channel.closeFuture().await(1000);
} finally {
// workerGroup.shutdownGracefully();
}
}
public Channel getChannel(){
return channel;
}
public static ThreeUdpClient getInstance(){
return logPushUdpClient.INSTANCE;
}
private static final class logPushUdpClient{
static final ThreeUdpClient INSTANCE = new ThreeUdpClient();
}
private ThreeUdpClient(){
bootstrap = new Bootstrap();
workerGroup = new NioEventLoopGroup();
bootstrap.group(workerGroup)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new ChannelInitializer() {
@Override
protected void initChannel(NioDatagramChannel ch)throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ThreeUdpClientDecoder(ASCII));
pipeline.addLast(new StringEncoder(ASCII));
pipeline.addLast(new ThreeUdpClientHandler());
}
});
}
}
6.ThreeUdpClientHandler
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.List;
/**
* 说 明:
*/
@Slf4j
public class ThreeUdpClientHandler extends SimpleChannelInboundHandler
7.自定义解码器ThreeUdpClientDecoder
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.internal.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class ThreeUdpClientDecoder extends MessageToMessageDecoder {
private final Charset charset;
public ThreeUdpClientDecoder() {
this(Charset.defaultCharset());
}
public ThreeUdpClientDecoder(Charset charset) {
this.charset = (Charset) ObjectUtil.checkNotNull(charset, "charset");
}
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, DatagramPacket packet, List
8.ThreeUdpClientTest
@Slf4j
public class ThreeUdpClientTest {
//服务端IP
private static final String server_host = "192.168.1.184";
//服务端端口 (UDP有效端口范围在 0-65535之间)
private static final int server_port = 60000;
public static void main(String[] args) {
try {
//启动ud客户端并定点端口
ThreeUdpClient.getInstance().start(1000);
int i = 0;
while( i < 10){
ThreeUdpClientHandler.sendMessage(new String("Hello UdpServer!!!"), new InetSocketAddress(server_host,server_port));
log.info(i+" client send message is: Hello UdpServer");
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果;依次运行ThreeUdpServerTest 和 ThreeUdpClientTest,效果如下:
服务daunt收到客户端的数据:
客户端向服务端发送消息,并得到回应
至此,简单的UDP实现到此结束, 至于更深奥的,博主任在努力学习中......