Skip to content

Commit

Permalink
add NettyDemo
Browse files Browse the repository at this point in the history
milovetingting committed Apr 12, 2020
1 parent dcbd398 commit 549355d
Showing 26 changed files with 313 additions and 1 deletion.
7 changes: 7 additions & 0 deletions NettyDemo/.classpath
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="lib" path="libs/netty-all-4.1.48.Final.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
17 changes: 17 additions & 0 deletions NettyDemo/.project
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>NettyDemo</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
2 changes: 2 additions & 0 deletions NettyDemo/.settings/org.eclipse.core.resources.prefs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8
11 changes: 11 additions & 0 deletions NettyDemo/.settings/org.eclipse.jdt.core.prefs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8
Binary file added NettyDemo/bin/com/wangyz/netty/Main.class
Binary file not shown.
Binary file added NettyDemo/bin/com/wangyz/netty/client/Config.class
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added NettyDemo/bin/com/wangyz/netty/server/Config.class
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added NettyDemo/libs/netty-all-4.1.48.Final.jar
Binary file not shown.
22 changes: 22 additions & 0 deletions NettyDemo/src/com/wangyz/netty/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.wangyz.netty;

import com.wangyz.netty.client.NettyClient;
import com.wangyz.netty.server.NettyServer;

public class Main {

public static void main(String[] args) {
try {
String host = "127.0.0.1";
int port = 12345;
NettyServer server = new NettyServer(port);
server.run();
Thread.sleep(1000);
NettyClient client = new NettyClient(host, port);
client.connect();
} catch (Exception e) {
e.printStackTrace();
}
}

}
5 changes: 5 additions & 0 deletions NettyDemo/src/com/wangyz/netty/client/Config.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.wangyz.netty.client;

public class Config {
public static final String DATA_PACK_SEPARATOR = "#$&*";
}
68 changes: 68 additions & 0 deletions NettyDemo/src/com/wangyz/netty/client/NettyClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.wangyz.netty.client;

import com.wangyz.netty.client.util.LogUtil;
import com.wangyz.netty.server.Config;

import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

public class NettyClient {

private String mHost;

private int mPort;

private NettyClientHandler mClientHandler;

private ChannelFuture mChannelFuture;

public NettyClient(String host, int port) {
this.mHost = host;
this.mPort = port;
}

public void connect() {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
mClientHandler = new NettyClientHandler();
b.group(workerGroup).channel(NioSocketChannel.class)
// KeepAlive
.option(ChannelOption.SO_KEEPALIVE, true)
// Handler
.handler(new ChannelInitializer<SocketChannel>() {

@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new IdleStateHandler(5, 5, 10));
// 这个配置需要在添加Handler前设置
channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,
Unpooled.copiedBuffer(Config.DATA_PACK_SEPARATOR.getBytes())));
channel.pipeline().addLast("encoder", new StringEncoder());
channel.pipeline().addLast("decoder", new StringDecoder());
channel.pipeline().addLast(mClientHandler);
}
});
mChannelFuture = b.connect(mHost, mPort).sync();
if (mChannelFuture.isSuccess()) {
LogUtil.log("Client,连接服务端成功");
}
mChannelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
}
}
}
51 changes: 51 additions & 0 deletions NettyDemo/src/com/wangyz/netty/client/NettyClientHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.wangyz.netty.client;

import com.wangyz.netty.client.util.LogUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
LogUtil.log("Client,channelActive");
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
LogUtil.log("Client,接收到服务端发来的消息:" + msg);
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LogUtil.log("Client,exceptionCaught");
cause.printStackTrace();
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
LogUtil.log("Client,channelInactive");
}

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
IdleStateEvent event = (IdleStateEvent) evt;
LogUtil.log("Client,Idle:" + event.state());
switch (event.state()) {
case READER_IDLE:

break;
case WRITER_IDLE:
ctx.writeAndFlush("心跳^v^" + Config.DATA_PACK_SEPARATOR);
break;
case ALL_IDLE:
break;
default:
super.userEventTriggered(ctx, evt);
break;
}
}

}
12 changes: 12 additions & 0 deletions NettyDemo/src/com/wangyz/netty/client/util/LogUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.wangyz.netty.client.util;

import java.util.Date;

public class LogUtil {

@SuppressWarnings("deprecation")
public static void log(Object msg) {
System.out.println(new Date().toLocaleString() + "--" + msg);
}

}
5 changes: 5 additions & 0 deletions NettyDemo/src/com/wangyz/netty/server/Config.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.wangyz.netty.server;

public class Config {
public static final String DATA_PACK_SEPARATOR = "#$&*";
}
64 changes: 64 additions & 0 deletions NettyDemo/src/com/wangyz/netty/server/NettyServer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.wangyz.netty.server;

import com.wangyz.netty.server.util.LogUtil;

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.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

public class NettyServer {

private int mPort;

public NettyServer(int port) {
this.mPort = port;
}

public void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
// 指定连接队列大小
.option(ChannelOption.SO_BACKLOG, 128)
// KeepAlive
.childOption(ChannelOption.SO_KEEPALIVE, true)
// Handler
.childHandler(new ChannelInitializer<SocketChannel>() {

@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new IdleStateHandler(5, 5, 10));
//这个配置需要在添加Handler前设置
channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,
Unpooled.copiedBuffer(Config.DATA_PACK_SEPARATOR.getBytes())));
channel.pipeline().addLast("encoder", new StringEncoder());
channel.pipeline().addLast("decoder", new StringDecoder());
channel.pipeline().addLast(new NettyServerHandler());
}
});
ChannelFuture f = b.bind(mPort).sync();
if (f.isSuccess()) {
LogUtil.log("Server,启动Netty服务端成功,端口号:" + mPort);
}
// f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
// workerGroup.shutdownGracefully();
// bossGroup.shutdownGracefully();
}
}

}
32 changes: 32 additions & 0 deletions NettyDemo/src/com/wangyz/netty/server/NettyServerHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.wangyz.netty.server;

import com.wangyz.netty.server.util.LogUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
LogUtil.log("Server,channelActive");
ctx.writeAndFlush("你好,客户端" + Config.DATA_PACK_SEPARATOR);
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
LogUtil.log("Server,接收到客户端发来的消息:" + msg);
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LogUtil.log("Server,exceptionCaught");
cause.printStackTrace();
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
LogUtil.log("Server,channelInactive");
}

}
12 changes: 12 additions & 0 deletions NettyDemo/src/com/wangyz/netty/server/util/LogUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.wangyz.netty.server.util;

import java.util.Date;

public class LogUtil {

@SuppressWarnings("deprecation")
public static void log(Object msg) {
System.out.println(new Date().toLocaleString() + "--" + msg);
}

}
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -54,4 +54,8 @@ Android中插件化简单实现:启动未注册的Activity

### 14、应用加固的简单实现方案

应用加固的简单实现方案
应用加固的简单实现方案

### 15、NettyDemo

基于Netty实现服务端与客户端通信

0 comments on commit 549355d

Please sign in to comment.