HeartBeatReqHandler.java
package com.demo.netty.client;
import java.util.concurrent.TimeUnit;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class HeartBeatReqHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
String message = (String) msg;
if (!message.contains("heart")) {
ctx.fireChannelRead(msg);
return;
}
System.out.println("HeartBeatReqHandler: " + message);
ctx.writeAndFlush(Unpooled.copiedBuffer("pipe1_client $_".getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.executor().scheduleAtFixedRate(new HeartBeatTask(ctx), 0, 90000, TimeUnit.MILLISECONDS);
}
private class HeartBeatTask implements Runnable {
private final ChannelHandlerContext ctx;
public HeartBeatTask(final ChannelHandlerContext ctx) {
this.ctx = ctx;
}
public void run() {
ctx.writeAndFlush(Unpooled.copiedBuffer("heartBeat$_".getBytes()));
}
}
}
NettyClient.java
package com.demo.netty.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.ReadTimeoutHandler;
public class NettyClient {
public static Channel ch;
private String host;
private int port;
public NettyClient(String host, int port) {
super();
this.host = host;
this.port = port;
}
public void start() {
try {
new Thread(new NettyRunnable()).start();
} catch (Exception e) {
e.printStackTrace();
}
}
private class NettyRunnable implements Runnable {
public void run() {
while (true) {
System.out.println("启动线程,连接" + host + ":" + port);
try {
NettyClient.connect(host, port);
} catch (Exception e) {
try {
Thread.sleep(6000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
}
public static synchronized void connect(String host, int port) throws Exception {
if (host == null || port < 0) {
throw new NullPointerException("socket unconnected");
}
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 6000).handler(new ClientChildChannelHandler());
ch = b.connect(host, port).sync().channel();
ch.closeFuture().sync();
System.out.println("................断开连接................");
} finally {
group.shutdownGracefully();
}
}
private static class ClientChildChannelHandler extends ChannelInitializer {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 使用长度依赖的话需要在数据包前声明数据包的长度
// ch.pipeline().addLast("lengthField",
// new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2));
// 换行分割
// ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
// ch.pipeline().addLast(new StringDecoder());
// 自定义分割符
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("$_".getBytes())));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new ReadTimeoutHandler(300));
ch.pipeline().addLast(new HeartBeatReqHandler());
ch.pipeline().addLast(new Pipe1ClientHandler());
ch.pipeline().addLast(new Pipe2ClientHandler());
}
}
public static void main(String[] args) {
new NettyClient("127.0.0.1", 55025).start();
}
}
Pipe1ClientHandler.java
package com.demo.netty.client;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class Pipe1ClientHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
String message = (String) msg;
if (!message.contains("pipe1")) {
ctx.fireChannelRead(msg);
return;
}
System.out.println("Pipe1ClientHandler: " + message);
ctx.writeAndFlush(Unpooled.copiedBuffer("pipe2_client $_".getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
Pipe2ClientHandler.java
package com.demo.netty.client;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class Pipe2ClientHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
String message = (String) msg;
if (!message.contains("pipe2")) {
ctx.fireChannelRead(msg);
return;
}
System.out.println("Pipe2ClientHandler: " + message);
ctx.writeAndFlush(Unpooled.copiedBuffer("pipe3_server $_".getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.demogroupId>
<artifactId>netty-clientartifactId>
<version>0.0.1-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>io.nettygroupId>
<artifactId>netty-allartifactId>
<version>5.0.0.Alpha1version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.5.1version>
<configuration>
<source>1.7source>
<target>1.7target>
<encoding>UTF-8encoding>
configuration>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-source-pluginartifactId>
<version>3.0.1version>
<executions>
<execution>
<id>attach-sourcesid>
<goals>
<goal>jargoal>
goals>
execution>
executions>
plugin>
plugins>
build>
project>
netty-client 实例源码
HeartBeatResHandler.java
package com.demo.netty.server;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class HeartBeatResHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
String message = (String) msg;
if (!message.contains("heart")) {
ctx.fireChannelRead(msg);
return;
}
System.out.println("HeartBeatResHandler:" + message);
ctx.writeAndFlush(Unpooled.copiedBuffer("heartBeat$_".getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
NettyServer.java
package com.demo.netty.server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.ReadTimeoutHandler;
public class NettyServer {
public void bind(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ServerChildChannelHandler());
ChannelFuture f = b.bind(port).sync();
System.out.println("NettyServer:"+ port);
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private class ServerChildChannelHandler extends ChannelInitializer {
protected void initChannel(SocketChannel ch) throws Exception {
// 使用长度依赖的话需要在数据包前声明数据包的长度
// ch.pipeline().addLast("lengthField",
// new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2));
// 换行分割
// ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
// ch.pipeline().addLast(new StringDecoder());
// 自定义分割符
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("$_".getBytes())));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new ReadTimeoutHandler(300));
ch.pipeline().addLast(new HeartBeatResHandler());
ch.pipeline().addLast(new Pipe1ServerHandler());
ch.pipeline().addLast(new Pipe2ServerHandler());
}
}
public static void main(String[] args) throws Exception {
new NettyServer().bind(55025);
}
}
Pipe1ServerHandler.java
package com.demo.netty.server;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class Pipe1ServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
String message = (String) msg;
if (!message.contains("pipe1")) {
ctx.fireChannelRead(msg);
return;
}
System.out.println("Pipe1ServerHandler: " + message);
ctx.writeAndFlush(Unpooled.copiedBuffer("pipe1_server $_".getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
Pipe2ServerHandler.java
package com.demo.netty.server;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class Pipe2ServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
String message = (String) msg;
if (!message.contains("pipe2")) {
System.out.println("fireChannelRead:" + message);
ctx.fireChannelRead(msg);
return;
}
System.out.println("Pipe2ServerHandler: " + message);
ctx.writeAndFlush(Unpooled.copiedBuffer("pipe2_server $_".getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.demogroupId>
<artifactId>netty-serverartifactId>
<version>0.0.1-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>io.nettygroupId>
<artifactId>netty-allartifactId>
<version>5.0.0.Alpha1version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.5.1version>
<configuration>
<source>1.7source>
<target>1.7target>
<encoding>UTF-8encoding>
configuration>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-source-pluginartifactId>
<version>3.0.1version>
<executions>
<execution>
<id>attach-sourcesid>
<goals>
<goal>jargoal>
goals>
execution>
executions>
plugin>
plugins>
build>
project>
netty-server 实例源码
https://blog.csdn.net/u010853261/article/details/55803933