服務端代碼:
EchoServer 啓動類
package com.tcp.echo;
/**
* @Description TODO
* @Date 2020/4/15 19:08
* @Author zsj
*/
import java.nio.charset.Charset;
import io.netty.bootstrap.ServerBootstrap;
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.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
public class EchoServer {
private final int port;
public EchoServer(int port) {
this.port = port;
}
public static void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap sb = new ServerBootstrap();
sb.option(ChannelOption.SO_BACKLOG, 1024);
sb.group(group, bossGroup) // 綁定線程池
.channel(NioServerSocketChannel.class) // 指定使用的channel
.localAddress(11111)// 綁定監聽端口
.childHandler(new ChannelInitializer<SocketChannel>() { // 綁定客戶端連接時候觸發操作
@Override
protected void initChannel(SocketChannel ch) throws Exception {
System.out.println("報告");
System.out.println("信息:有一客戶端鏈接到本服務端");
System.out.println("IP:" + ch.localAddress().getHostName());
System.out.println("Port:" + ch.localAddress().getPort());
System.out.println("報告完畢");
ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
ch.pipeline().addLast(new EchoServerHandler()); // 客戶端觸發操作
ch.pipeline().addLast(new ByteArrayEncoder());
}
});
ChannelFuture cf = sb.bind().sync(); // 服務器異步創建綁定
System.out.println(EchoServer.class + " 啓動正在監聽: " + cf.channel().localAddress());
cf.channel().closeFuture().sync(); // 關閉服務器通道
} finally {
group.shutdownGracefully().sync(); // 釋放線程池資源
bossGroup.shutdownGracefully().sync();
}
}
public static void main(String[] args) {
try {
EchoServer.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
服務端消息處理邏輯
EchoServerHandler
package com.tcp.echo;
/**
* @Description TODO
* @Date 2020/4/15 19:10
* @Author zsj
*/
import java.io.UnsupportedEncodingException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
/*
* channelAction
*
* channel 通道 action 活躍的
*
* 當客戶端主動鏈接服務端的鏈接後,這個通道就是活躍的了。也就是客戶端與服務端建立了通信通道並且可以傳輸數據
*
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().localAddress().toString() + " 通道已激活!");
}
/*
* channelInactive
*
* channel 通道 Inactive 不活躍的
*
* 當客戶端主動斷開服務端的鏈接後,這個通道就是不活躍的。也就是說客戶端與服務端的關閉了通信通道並且不可以傳輸數據
*
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().localAddress().toString() + " 通道不活躍!");
// 關閉流
}
/**
* @param buf
* @return
* @author Taowd
* TODO 此處用來處理收到的數據中含有中文的時 出現亂碼的問題
* 2017年8月31日 下午7:57:28
*/
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
/**
* 功能:讀取服務器發送過來的信息
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 第一種:接收字符串時的處理
ByteBuf buf = (ByteBuf) msg;
String rev = getMessage(buf);
System.out.println("接收到客戶端發來的數據:" + rev);
}
/**
* 功能:讀取完畢客戶端發送過來的數據之後的操作
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("服務端接收數據完畢..");
}
/**
* 功能:服務端發生異常的操作
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
cause.printStackTrace();
}
}
客戶端代碼 整合springboot
EchoClient
package com.tcp.echo;
/**
* @Description TODO
* @Date 2020/4/15 19:13
* @Author zsj
*/
import java.util.concurrent.TimeUnit;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component
public class EchoClient {
private String host = "127.0.0.1";
private Integer port = 11111;
private EventLoopGroup group;
private ChannelFuture f;
/**
* Netty創建全部都是實現自AbstractBootstrap。 客戶端的是Bootstrap,服務端的則是 ServerBootstrap。
**/
@PostConstruct
public void init() {
group = new NioEventLoopGroup();
doConnect(new Bootstrap(), group);
}
@PreDestroy
public void shutdown() throws InterruptedException {
System.out.println("正在停止客戶端");
try {
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
System.out.println("客戶端已停止!");
}
public void doConnect(Bootstrap bootstrap, EventLoopGroup eventLoopGroup) {
try {
if (bootstrap != null) {
bootstrap.group(eventLoopGroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.handler(new EchoClientInitializer());
bootstrap.remoteAddress(host, port);
f = bootstrap.connect().addListener((ChannelFuture futureListener) -> {
final EventLoop eventLoop = futureListener.channel().eventLoop();
if (!futureListener.isSuccess()) {
System.out.println(port + "與服務端斷開連接!在10s之後準備嘗試重連!");
eventLoop.schedule(() -> doConnect(new Bootstrap(), eventLoop), 10, TimeUnit.SECONDS);
} else {
System.out.println(port + "Netty客戶端啓動成功!");
}
});
}
} catch (Exception e) {
System.out.println("客戶端連接失敗!" + e.getMessage());
}
}
public boolean sendMsg(String msg) {
if (f != null && f.channel() != null && f.channel().isActive()) {
ChannelFuture channelFuture = null;
try {
channelFuture = f.channel().writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)).sync();
} catch (InterruptedException e) {
return false;
}
return channelFuture.isSuccess();
} else {
return false;
}
}
}
客戶端初始化
EchoClientInitializer
package com.tcp.echo;
/**
* @Description TODO
* @Date 2019/10/18 10:05
* @Author zsj
*/
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
public class EchoClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline ph = ch.pipeline();
/*
* 解碼和編碼,應和服務端一致
* */
//入參說明: 讀超時時間、寫超時時間、所有類型的超時時間、時間格式
ph.addLast(new IdleStateHandler(0, 30, 0, TimeUnit.SECONDS));
//傳輸的協議 Protobuf
System.out.println("正在連接中...");
ph.addLast(new StringEncoder(Charset.forName("GBK")));
ph.addLast(new EchoClientHandler());
ph.addLast(new ByteArrayEncoder());
ph.addLast(new ChunkedWriteHandler());
}
}
客戶端消息處理邏輯
EchoClientHandler
package com.tcp.echo;
/**
* @Description TODO
* @Date 2020/4/15 19:14
* @Author zsj
*/
import java.nio.charset.Charset;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import com.pancm.protobuf.UserInfo;
import com.tcp.SpringContextUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
@ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
EchoClient echoClient;
/** 循環次數 */
private AtomicInteger fcount = new AtomicInteger(1);
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("客戶端與服務端通道-開啓:" + ctx.channel().localAddress() + "channelActive");
}
/**
* channelInactive
* <p>
* channel 通道 Inactive 不活躍的
* <p>
* 當客戶端主動斷開服務端的鏈接後,這個通道就是不活躍的。也就是說客戶端與服務端的關閉了通信通道並且不可以傳輸數據
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) {
System.out.println("客戶端與服務端通道-關閉:" + ctx.channel().localAddress() + "channelInactive");
final EventLoop eventLoop = ctx.channel().eventLoop();
if (echoClient == null){
echoClient = (EchoClient) SpringContextUtil.getBean(EchoClient.class);
}
echoClient.doConnect(new Bootstrap(), eventLoop);
try {
super.channelInactive(ctx);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg){
System.out.println("讀取服務端發來的通道信息..");
ByteBuf buf = msg.readBytes(msg.readableBytes());
System.out.println(
"客戶端接收到的服務端信息:" + ByteBufUtil.hexDump(buf) + "; 數據包爲:" + buf.toString(Charset.forName("utf-8")));
}
/**
* 心跳請求處理 每30秒發送一次心跳請求;
*
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object obj) {
System.out.println("循環請求的時間:" + new Date() + ",次數" + fcount.get());
if (obj instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) obj;
// 如果寫通道處於空閒狀態,就發送心跳命令
if (IdleState.WRITER_IDLE.equals(event.state())) {
ctx.channel().writeAndFlush("xintao");
fcount.getAndIncrement();
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
System.out.println("異常退出:" + cause.getMessage());
}
}
客戶端發消息給服務端
HandController
package com.tcp.controller;
import com.tcp.echo.EchoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HandController {
@Autowired
EchoClient echoClient;
@GetMapping("/echo")
public String sentMsg() {
boolean flag = echoClient.sendMsg("2344343");
return flag+"";
}
}