├── .gitignore
├── .idea
├── compiler.xml
├── gradle.xml
├── misc.xml
├── modules.xml
└── runConfigurations.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── libs
│ └── netty-all-4.1.23.Final.jar
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── ifreecomm
│ │ └── nettydemo
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── ifreecomm
│ │ │ └── nettydemo
│ │ │ ├── Const.java
│ │ │ ├── MainActivity.java
│ │ │ ├── NettyClient.java
│ │ │ ├── NettyClientHandler.java
│ │ │ ├── NettyListener.java
│ │ │ ├── adapter
│ │ │ └── LogAdapter.java
│ │ │ └── bean
│ │ │ └── LogBean.java
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ └── log_item.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── ifreecomm
│ └── nettydemo
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── nettyserver
├── .gitignore
├── build.gradle
├── libs
│ └── netty-all-4.1.23.Final.jar
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── ifreecomm
│ │ └── nettyserver
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── ifreecomm
│ │ │ └── nettyserver
│ │ │ ├── EchoServer.java
│ │ │ ├── EchoServerHandler.java
│ │ │ ├── MainActivity.java
│ │ │ ├── NettyListener.java
│ │ │ ├── adapter
│ │ │ └── LogAdapter.java
│ │ │ └── bean
│ │ │ └── LogBean.java
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ └── log_item.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── ifreecomm
│ └── nettyserver
│ └── ExampleUnitTest.java
├── screenshot
├── clent.gif
└── server.gif
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 | 1.8
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # NettyDemo
2 |
3 | Netty是基于Java NIO client-server的网络应用框架,使用Netty可以快速开发网络应用
4 | 更多用法请请跳转到https://github.com/netty/netty
5 |
6 | 本项目基于Netty在Android平台所建项目,供大家参考学习
7 |
8 | 
9 | 
10 |
11 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 26
5 | defaultConfig {
6 | applicationId "ifreecomm.nettydemo"
7 | minSdkVersion 18
8 | targetSdkVersion 26
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | implementation fileTree(include: ['*.jar'], dir: 'libs')
23 | implementation 'com.android.support:appcompat-v7:26.1.0'
24 | compile 'com.android.support:design:26.1.0'
25 | implementation 'com.android.support.constraint:constraint-layout:1.0.2'
26 | testImplementation 'junit:junit:4.12'
27 | androidTestImplementation 'com.android.support.test:runner:1.0.1'
28 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
29 | implementation files('libs/netty-all-4.1.23.Final.jar')
30 | }
31 |
--------------------------------------------------------------------------------
/app/libs/netty-all-4.1.23.Final.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/app/libs/netty-all-4.1.23.Final.jar
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/ifreecomm/nettydemo/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettydemo;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("ifreecomm.nettydemo", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
16 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/java/ifreecomm/nettydemo/Const.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettydemo;
2 |
3 |
4 |
5 | public class Const {
6 |
7 | public static final String HOST = "172.16.8.233";
8 | public static final int TCP_PORT = 1088;
9 | }
10 |
--------------------------------------------------------------------------------
/app/src/main/java/ifreecomm/nettydemo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettydemo;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.support.v7.widget.LinearLayoutManager;
6 | import android.support.v7.widget.RecyclerView;
7 | import android.text.TextUtils;
8 | import android.util.Log;
9 | import android.view.View;
10 | import android.widget.Button;
11 | import android.widget.EditText;
12 | import android.widget.Toast;
13 |
14 | import ifreecomm.nettydemo.adapter.LogAdapter;
15 | import ifreecomm.nettydemo.bean.LogBean;
16 | import io.netty.channel.ChannelFuture;
17 | import io.netty.channel.ChannelFutureListener;
18 |
19 | import static android.widget.Toast.LENGTH_SHORT;
20 |
21 | public class MainActivity extends AppCompatActivity implements View.OnClickListener, NettyListener {
22 |
23 | private static final String TAG = "MainActivity";
24 | private Button mClearLog;
25 | private Button mSendBtn;
26 | private Button mConnect;
27 | private EditText mSendET;
28 | private RecyclerView mSendList;
29 | private RecyclerView mReceList;
30 |
31 | private LogAdapter mSendLogAdapter = new LogAdapter();
32 | private LogAdapter mReceLogAdapter = new LogAdapter();
33 | private NettyClient mNettyClient;
34 |
35 | @Override
36 | protected void onCreate(Bundle savedInstanceState) {
37 | super.onCreate(savedInstanceState);
38 | setContentView(R.layout.activity_main);
39 | findViews();
40 | initData();
41 | initlistener();
42 | mNettyClient = new NettyClient(Const.HOST, Const.TCP_PORT);
43 | }
44 |
45 | private void initlistener() {
46 |
47 |
48 | }
49 |
50 | private void initData() {
51 | LinearLayoutManager manager1 = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
52 | mSendList.setLayoutManager(manager1);
53 | mSendList.setAdapter(mSendLogAdapter);
54 |
55 | LinearLayoutManager manager2 = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
56 | mReceList.setLayoutManager(manager2);
57 | mReceList.setAdapter(mReceLogAdapter);
58 |
59 | }
60 |
61 | private void findViews() {
62 | mSendList = findViewById(R.id.send_list);
63 | mReceList = findViewById(R.id.rece_list);
64 | mSendET = findViewById(R.id.send_et);
65 | mConnect = findViewById(R.id.connect);
66 | mSendBtn = findViewById(R.id.send_btn);
67 | mClearLog = findViewById(R.id.clear_log);
68 |
69 | mConnect.setOnClickListener(this);
70 | mSendBtn.setOnClickListener(this);
71 | mClearLog.setOnClickListener(this);
72 | }
73 |
74 | @Override
75 | public void onClick(View v) {
76 | switch (v.getId()) {
77 |
78 | case R.id.connect:
79 | connect();
80 | break;
81 |
82 | case R.id.send_btn:
83 | if (!mNettyClient.getConnectStatus()) {
84 | Toast.makeText(getApplicationContext(), "未连接,请先连接", LENGTH_SHORT).show();
85 | } else {
86 | final String msg = mSendET.getText().toString();
87 | if (TextUtils.isEmpty(msg.trim())) {
88 | return;
89 | }
90 | mNettyClient.sendMsgToServer(msg, new ChannelFutureListener() {
91 | @Override
92 | public void operationComplete(ChannelFuture channelFuture) throws Exception {
93 | if (channelFuture.isSuccess()) { //4
94 | Log.d(TAG, "Write auth successful");
95 | logSend(msg);
96 | } else {
97 | Log.d(TAG, "Write auth error");
98 | }
99 | }
100 | });
101 | mSendET.setText("");
102 | }
103 |
104 | break;
105 |
106 | case R.id.clear_log:
107 | mReceLogAdapter.getDataList().clear();
108 | mSendLogAdapter.getDataList().clear();
109 | mReceLogAdapter.notifyDataSetChanged();
110 | mSendLogAdapter.notifyDataSetChanged();
111 | break;
112 | }
113 | }
114 |
115 | private void connect() {
116 | Log.d(TAG, "connect");
117 | if (!mNettyClient.getConnectStatus()) {
118 | mNettyClient.setListener(MainActivity.this);
119 | mNettyClient.connect();//连接服务器
120 | } else {
121 | mNettyClient.disconnect();
122 | }
123 | }
124 |
125 | @Override
126 | public void onMessageResponse(Object msg) {
127 | Log.e(TAG, "onMessageResponse:" + msg);
128 | logRece((String) msg);
129 | // byte[] bytes = byteBuf.array();
130 | //
131 | // String hexFun3 = bytesToHexFun3(bytes, byteBuf.writerIndex());
132 | // logRece(hexFun3);
133 | }
134 |
135 | @Override
136 | public void onServiceStatusConnectChanged(final int statusCode) {
137 | runOnUiThread(new Runnable() {
138 | @Override
139 | public void run() {
140 | if (statusCode == NettyListener.STATUS_CONNECT_SUCCESS) {
141 | Log.e(TAG, "STATUS_CONNECT_SUCCESS:");
142 | mConnect.setText("DisConnect");
143 | } else {
144 | Log.e(TAG, "onServiceStatusConnectChanged:" + statusCode);
145 | mConnect.setText("Connect");
146 | }
147 | }
148 | });
149 |
150 | }
151 |
152 | private void logSend(String log) {
153 | LogBean logBean = new LogBean(System.currentTimeMillis(), log);
154 | mSendLogAdapter.getDataList().add(0, logBean);
155 | runOnUiThread(new Runnable() {
156 | @Override
157 | public void run() {
158 | mSendLogAdapter.notifyDataSetChanged();
159 | }
160 | });
161 |
162 | }
163 |
164 | private void logRece(String log) {
165 | LogBean logBean = new LogBean(System.currentTimeMillis(), log);
166 | mReceLogAdapter.getDataList().add(0, logBean);
167 | runOnUiThread(new Runnable() {
168 | @Override
169 | public void run() {
170 | mReceLogAdapter.notifyDataSetChanged();
171 | }
172 | });
173 |
174 | }
175 |
176 | /**
177 | * 方法三:
178 | * byte[] to hex string
179 | *
180 | * @param bytes
181 | * @return
182 | */
183 | public static String bytesToHexFun3(byte[] bytes, int length) {
184 | StringBuilder buf = new StringBuilder(length * 2);
185 | for (int i = 0; i < length; i++) {// 使用String的format方法进行转换
186 |
187 | buf.append(String.format("%02x", new Integer(bytes[i] & 0xFF)));
188 | }
189 | return buf.toString();
190 | }
191 |
192 | public void disconnect(View view) {
193 | mNettyClient.disconnect();
194 | }
195 | }
196 |
--------------------------------------------------------------------------------
/app/src/main/java/ifreecomm/nettydemo/NettyClient.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettydemo;
2 |
3 | import android.os.SystemClock;
4 | import android.util.Log;
5 |
6 | import java.util.concurrent.TimeUnit;
7 |
8 | import io.netty.bootstrap.Bootstrap;
9 | import io.netty.buffer.ByteBuf;
10 | import io.netty.buffer.Unpooled;
11 | import io.netty.channel.Channel;
12 | import io.netty.channel.ChannelFuture;
13 | import io.netty.channel.ChannelFutureListener;
14 | import io.netty.channel.ChannelInitializer;
15 | import io.netty.channel.ChannelOption;
16 | import io.netty.channel.EventLoopGroup;
17 | import io.netty.channel.nio.NioEventLoopGroup;
18 | import io.netty.channel.socket.SocketChannel;
19 | import io.netty.channel.socket.nio.NioSocketChannel;
20 | import io.netty.handler.codec.LineBasedFrameDecoder;
21 | import io.netty.handler.codec.string.StringDecoder;
22 | import io.netty.handler.codec.string.StringEncoder;
23 | import io.netty.handler.timeout.IdleStateHandler;
24 | import io.netty.util.CharsetUtil;
25 |
26 |
27 | public class NettyClient {
28 | private static final String TAG = "NettyClient";
29 |
30 | private EventLoopGroup group;
31 |
32 | private NettyListener listener;
33 |
34 | private Channel channel;
35 |
36 | private boolean isConnect = false;
37 |
38 | private static int reconnectNum = Integer.MAX_VALUE;
39 |
40 | private boolean isNeedReconnect = true;
41 | private boolean isConnecting = false;
42 |
43 | private long reconnectIntervalTime = 5000;
44 | private static final Integer CONNECT_TIMEOUT_MILLIS = 5000;
45 |
46 | public String host;
47 | public int tcp_port;
48 |
49 | // private ScheduledExecutorService mScheduledExecutorService;
50 |
51 | public NettyClient(String host, int tcp_port) {
52 | this.host = host;
53 | this.tcp_port = tcp_port;
54 | }
55 |
56 | public void connect() {
57 |
58 | if (isConnecting) {
59 | return;
60 | }
61 | Thread clientThread = new Thread("client-Netty") {
62 | @Override
63 | public void run() {
64 | super.run();
65 | isNeedReconnect = true;
66 | reconnectNum = Integer.MAX_VALUE;
67 | connectServer();
68 | }
69 | };
70 | clientThread.start();
71 | }
72 |
73 |
74 | private void connectServer() {
75 | synchronized (NettyClient.this) {
76 | ChannelFuture channelFuture = null;
77 | if (!isConnect) {
78 | isConnecting = true;
79 | group = new NioEventLoopGroup();
80 | Bootstrap bootstrap = new Bootstrap().group(group)
81 | .option(ChannelOption.TCP_NODELAY, true)//屏蔽Nagle算法试图
82 | .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
83 | .channel(NioSocketChannel.class)
84 | .handler(new ChannelInitializer() { // 5
85 | @Override
86 | public void initChannel(SocketChannel ch) throws Exception {
87 | ch.pipeline().addLast("ping", new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS));//5s未发送数据,回调userEventTriggered
88 | ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
89 | ch.pipeline().addLast(new LineBasedFrameDecoder(1024));//黏包处理
90 | ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
91 | ch.pipeline().addLast(new NettyClientHandler(listener));
92 | }
93 | });
94 |
95 | try {
96 | channelFuture = bootstrap.connect(host, tcp_port).addListener(new ChannelFutureListener() {
97 | @Override
98 | public void operationComplete(ChannelFuture channelFuture) throws Exception {
99 | if (channelFuture.isSuccess()) {
100 | Log.e(TAG,"连接成功");
101 | isConnect = true;
102 | channel = channelFuture.channel();
103 | } else {
104 | Log.e(TAG,"连接失败");
105 | isConnect = false;
106 | }
107 | isConnecting = false;
108 | }
109 | }).sync();
110 |
111 | // Wait until the connection is closed.
112 | channelFuture.channel().closeFuture().sync();
113 | Log.e(TAG, " 断开连接");
114 | } catch (Exception e) {
115 | e.printStackTrace();
116 | } finally {
117 | isConnect = false;
118 | listener.onServiceStatusConnectChanged(NettyListener.STATUS_CONNECT_CLOSED);
119 | if (null != channelFuture) {
120 | if (channelFuture.channel() != null && channelFuture.channel().isOpen()) {
121 | channelFuture.channel().close();
122 | }
123 | }
124 | group.shutdownGracefully();
125 | reconnect();
126 | }
127 | }
128 | }
129 | }
130 |
131 |
132 | public void disconnect() {
133 | Log.e(TAG, "disconnect");
134 | isNeedReconnect = false;
135 | group.shutdownGracefully();
136 | }
137 |
138 | public void reconnect() {
139 | Log.e(TAG, "reconnect");
140 | if (isNeedReconnect && reconnectNum > 0 && !isConnect) {
141 | reconnectNum--;
142 | SystemClock.sleep(reconnectIntervalTime);
143 | if (isNeedReconnect && reconnectNum > 0 && !isConnect) {
144 | Log.e(TAG, "重新连接");
145 | connectServer();
146 | }
147 | }
148 | }
149 |
150 | public boolean sendMsgToServer(String data, ChannelFutureListener listener) {
151 | boolean flag = channel != null && isConnect;
152 | if (flag) {
153 | // ByteBuf buf = Unpooled.copiedBuffer(data);
154 | // ByteBuf byteBuf = Unpooled.copiedBuffer(data + System.getProperty("line.separator"), //2
155 | // CharsetUtil.UTF_8);
156 | channel.writeAndFlush(data + System.getProperty("line.separator")).addListener(listener);
157 | }
158 | return flag;
159 | }
160 |
161 | public boolean sendMsgToServer(byte[] data, ChannelFutureListener listener) {
162 | boolean flag = channel != null && isConnect;
163 | if (flag) {
164 | ByteBuf buf = Unpooled.copiedBuffer(data);
165 | channel.writeAndFlush(buf).addListener(listener);
166 | }
167 | return flag;
168 | }
169 |
170 | public void setReconnectNum(int reconnectNum) {
171 | this.reconnectNum = reconnectNum;
172 | }
173 |
174 | public void setReconnectIntervalTime(long reconnectIntervalTime) {
175 | this.reconnectIntervalTime = reconnectIntervalTime;
176 | }
177 |
178 | public boolean getConnectStatus() {
179 | return isConnect;
180 | }
181 |
182 | public boolean isConnecting() {
183 | return isConnecting;
184 | }
185 |
186 | public void setConnectStatus(boolean status) {
187 | this.isConnect = status;
188 | }
189 |
190 | public void setListener(NettyListener listener) {
191 | this.listener = listener;
192 | }
193 |
194 | }
195 |
--------------------------------------------------------------------------------
/app/src/main/java/ifreecomm/nettydemo/NettyClientHandler.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettydemo;
2 |
3 | import android.util.Log;
4 |
5 | import io.netty.channel.ChannelHandlerContext;
6 | import io.netty.channel.SimpleChannelInboundHandler;
7 | import io.netty.handler.timeout.IdleState;
8 | import io.netty.handler.timeout.IdleStateEvent;
9 |
10 |
11 | public class NettyClientHandler extends SimpleChannelInboundHandler {
12 |
13 | private static final String TAG = "NettyClientHandler";
14 | private NettyListener listener;
15 |
16 | // private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Heartbeat"+System.getProperty("line.separator"),
17 | // CharsetUtil.UTF_8));
18 | // byte[] requestBody = {(byte) 0xFE, (byte) 0xED, (byte) 0xFE, 5,4, (byte) 0xFF,0x0a};
19 |
20 |
21 | public NettyClientHandler(NettyListener listener) {
22 | this.listener = listener;
23 | }
24 |
25 |
26 | @Override
27 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
28 | if (evt instanceof IdleStateEvent) {
29 | IdleStateEvent event = (IdleStateEvent) evt;
30 | if (event.state() == IdleState.WRITER_IDLE) {
31 | ctx.channel().writeAndFlush("Heartbeat"+System.getProperty("line.separator"));
32 | }
33 | }
34 | }
35 |
36 | /**
37 | * 连接成功
38 | *
39 | * @param ctx
40 | * @throws Exception
41 | */
42 | @Override
43 | public void channelActive(ChannelHandlerContext ctx) throws Exception {
44 | Log.e(TAG, "channelActive");
45 | // NettyClient.getInstance().setConnectStatus(true);
46 | listener.onServiceStatusConnectChanged(NettyListener.STATUS_CONNECT_SUCCESS);
47 | }
48 |
49 | @Override
50 | public void channelInactive(ChannelHandlerContext ctx) throws Exception {
51 | Log.e(TAG, "channelInactive");
52 | // NettyClient.getInstance().setConnectStatus(false);
53 | // listener.onServiceStatusConnectChanged(NettyListener.STATUS_CONNECT_CLOSED);
54 | // NettyClient.getInstance().reconnect();
55 | }
56 |
57 | /**
58 | * 客户端收到消息
59 | *
60 | * @param channelHandlerContext
61 | * @param byteBuf
62 | * @throws Exception
63 | */
64 | @Override
65 | protected void channelRead0(ChannelHandlerContext channelHandlerContext, String byteBuf) throws Exception {
66 | Log.e(TAG, "channelRead0");
67 | listener.onMessageResponse(byteBuf);
68 | }
69 |
70 | @Override
71 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
72 | // Close the connection when an exception is raised.
73 | // NettyClient.getInstance().setConnectStatus(false);
74 | Log.e(TAG, "exceptionCaught");
75 | listener.onServiceStatusConnectChanged(NettyListener.STATUS_CONNECT_ERROR);
76 | cause.printStackTrace();
77 | ctx.close();
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/app/src/main/java/ifreecomm/nettydemo/NettyListener.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettydemo;
2 |
3 |
4 |
5 | public interface NettyListener {
6 |
7 | public final static byte STATUS_CONNECT_SUCCESS = 1;
8 |
9 | public final static byte STATUS_CONNECT_CLOSED = 0;
10 |
11 | public final static byte STATUS_CONNECT_ERROR = 0;
12 |
13 |
14 | /**
15 | * 当接收到系统消息
16 | */
17 | void onMessageResponse(Object msg);
18 |
19 | /**
20 | * 当服务状态发生变化时触发
21 | */
22 | public void onServiceStatusConnectChanged(int statusCode);
23 | }
24 |
--------------------------------------------------------------------------------
/app/src/main/java/ifreecomm/nettydemo/adapter/LogAdapter.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettydemo.adapter;
2 |
3 | import android.content.ClipData;
4 | import android.content.ClipboardManager;
5 | import android.content.Context;
6 | import android.support.v7.widget.RecyclerView;
7 | import android.view.LayoutInflater;
8 | import android.view.View;
9 | import android.view.ViewGroup;
10 | import android.widget.TextView;
11 | import android.widget.Toast;
12 |
13 | import java.util.ArrayList;
14 | import java.util.List;
15 |
16 | import ifreecomm.nettydemo.R;
17 | import ifreecomm.nettydemo.bean.LogBean;
18 |
19 | public class LogAdapter extends RecyclerView.Adapter {
20 |
21 | private List mDataList = new ArrayList<>();
22 |
23 | @Override
24 | public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
25 | return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.log_item, parent, false));
26 | }
27 |
28 | @Override
29 | public void onBindViewHolder(final ItemHolder holder, int position) {
30 | LogBean bean = mDataList.get(position);
31 |
32 | holder.mTime.setText(bean.mTime);
33 | holder.mLog.setText(bean.mLog);
34 |
35 | holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
36 | @Override
37 | public boolean onLongClick(View v) {
38 | ClipboardManager cmb = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
39 | LogBean log = mDataList.get(holder.getAdapterPosition());
40 | String msg = log.mTime + " " + log.mLog;
41 | cmb.setPrimaryClip(ClipData.newPlainText(null, msg));
42 | Toast.makeText(v.getContext(), "已复制到剪贴板", Toast.LENGTH_LONG).show();
43 | return true;
44 | }
45 | });
46 | }
47 |
48 | @Override
49 | public int getItemCount() {
50 | return mDataList.size();
51 | }
52 |
53 | public class ItemHolder extends RecyclerView.ViewHolder {
54 | public TextView mTime;
55 | public TextView mLog;
56 |
57 | public ItemHolder(View itemView) {
58 | super(itemView);
59 | mTime = (TextView) itemView.findViewById(R.id.time);
60 | mLog = (TextView) itemView.findViewById(R.id.logtext);
61 | }
62 | }
63 |
64 | public List getDataList() {
65 | return mDataList;
66 | }
67 | }
--------------------------------------------------------------------------------
/app/src/main/java/ifreecomm/nettydemo/bean/LogBean.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettydemo.bean;
2 |
3 | import java.text.SimpleDateFormat;
4 |
5 | public class LogBean {
6 | public String mTime;
7 | public String mLog;
8 |
9 | public LogBean(long time, String log) {
10 | SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
11 | mTime = format.format(time);
12 | mLog = log;
13 | }
14 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
12 |
13 |
17 |
18 |
19 |
23 |
24 |
29 |
30 |
36 |
37 |
42 |
43 |
47 |
48 |
56 |
57 |
65 |
66 |
74 |
75 |
76 |
77 |
81 |
82 |
91 |
92 |
98 |
99 |
100 |
101 |
102 |
103 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/log_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
13 |
14 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | NettyDemo
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/ifreecomm/nettydemo/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettydemo;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 |
5 | repositories {
6 | google()
7 | jcenter()
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:3.0.1'
11 |
12 |
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | google()
21 | jcenter()
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
27 | }
28 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Apr 10 14:58:54 CST 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/nettyserver/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/nettyserver/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 26
5 |
6 |
7 |
8 | defaultConfig {
9 | applicationId "ifreecomm.nettyserver"
10 | minSdkVersion 18
11 | targetSdkVersion 25
12 | versionCode 1
13 | versionName "1.0"
14 |
15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
16 |
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 |
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(include: ['*.jar'], dir: 'libs')
30 | implementation 'com.android.support:appcompat-v7:26.1.0'
31 | compile 'com.android.support:design:26.1.0'
32 | implementation 'com.android.support.constraint:constraint-layout:1.0.2'
33 | testImplementation 'junit:junit:4.12'
34 | androidTestImplementation 'com.android.support.test:runner:1.0.1'
35 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
36 | implementation files('libs/netty-all-4.1.23.Final.jar')
37 | }
38 |
--------------------------------------------------------------------------------
/nettyserver/libs/netty-all-4.1.23.Final.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/nettyserver/libs/netty-all-4.1.23.Final.jar
--------------------------------------------------------------------------------
/nettyserver/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/nettyserver/src/androidTest/java/ifreecomm/nettyserver/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettyserver;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("ifreecomm.nettyserver", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/nettyserver/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/nettyserver/src/main/java/ifreecomm/nettyserver/EchoServer.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettyserver;
2 |
3 | import android.util.Log;
4 |
5 | import java.net.InetSocketAddress;
6 |
7 | import io.netty.bootstrap.ServerBootstrap;
8 | import io.netty.channel.Channel;
9 | import io.netty.channel.ChannelFuture;
10 | import io.netty.channel.ChannelFutureListener;
11 | import io.netty.channel.ChannelInitializer;
12 | import io.netty.channel.ChannelOption;
13 | import io.netty.channel.EventLoopGroup;
14 | import io.netty.channel.nio.NioEventLoopGroup;
15 | import io.netty.channel.socket.SocketChannel;
16 | import io.netty.channel.socket.nio.NioServerSocketChannel;
17 | import io.netty.handler.codec.LineBasedFrameDecoder;
18 | import io.netty.handler.codec.string.StringDecoder;
19 | import io.netty.handler.codec.string.StringEncoder;
20 | import io.netty.util.CharsetUtil;
21 |
22 |
23 | public class EchoServer {
24 |
25 | private static final String TAG = "EchoServer";
26 | private final int port = 1088;
27 | private Channel channel;
28 |
29 | private static EchoServer instance = null;
30 | private NettyListener listener;
31 | private boolean connectStatus;
32 | private EventLoopGroup bossGroup;
33 | private EventLoopGroup workerGroup;
34 | private boolean isServerStart;
35 |
36 | public static EchoServer getInstance() {
37 | if (instance == null) {
38 | synchronized (EchoServer.class) {
39 | if (instance == null) {
40 | instance = new EchoServer();
41 | }
42 | }
43 | }
44 | return instance;
45 | }
46 |
47 | private EchoServer() {
48 | }
49 |
50 | /*public static void main(String[] args) throws Exception {
51 | int port = 1000;// Integer.parseInt(args[0]); //1
52 |
53 | new Thread() {
54 | public void run() {
55 | while (true) {
56 | InputStreamReader is = new InputStreamReader(System.in); // new����InputStreamReader����
57 | BufferedReader br = new BufferedReader(is); // �ù���ķ�������BufferedReader��
58 | try { // �÷������и�IOExcepiton��Ҫ����
59 | String name = br.readLine();
60 | if (channel != null && channel.isActive()) {
61 | // ByteBuf byteBuf = Unpooled.copiedBuffer(name+System.getProperty("line.separator"), // 2
62 | // CharsetUtil.UTF_8);
63 | channel.writeAndFlush(name+System.getProperty("line.separator")).addListener(new ChannelFutureListener() {
64 | @Override
65 | public void operationComplete(ChannelFuture channelFuture) throws Exception {
66 | if (channelFuture.isSuccess()) { // 4
67 | System.out.println("Write auth successful");
68 | } else {
69 | System.out.println("Write auth error");
70 | }
71 | }
72 | });
73 | }else {
74 | System.out.println("channel:"+channel);
75 | }
76 |
77 | } catch (IOException e) {
78 | e.printStackTrace();
79 | }
80 |
81 | }
82 | };
83 | }.start();
84 | new EchoServer(port).start();
85 | // 2
86 |
87 | }*/
88 |
89 | public void start() {
90 | bossGroup = new NioEventLoopGroup(1);
91 | workerGroup = new NioEventLoopGroup();
92 | try {
93 | ServerBootstrap b = new ServerBootstrap();
94 | b.group(bossGroup, workerGroup)
95 | .channel(NioServerSocketChannel.class) // 5
96 | .localAddress(new InetSocketAddress(port)) // 6
97 | .childOption(ChannelOption.SO_KEEPALIVE, true)
98 | .childOption(ChannelOption.SO_REUSEADDR,true)
99 | .childOption(ChannelOption.TCP_NODELAY,true)
100 | .childHandler(new ChannelInitializer() { // 7
101 |
102 | @Override
103 | public void initChannel(SocketChannel ch) throws Exception {
104 | System.out.println("initChannel ch:" + ch);
105 | ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
106 | ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
107 | ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
108 | ch.pipeline().addLast(new EchoServerHandler(listener));
109 | }
110 | });
111 |
112 | // Bind and start to accept incoming connections.
113 | ChannelFuture f = b.bind().sync(); // 8
114 |
115 | System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
116 | isServerStart = true;
117 | listener.onStartServer();
118 | // Wait until the server socket is closed.
119 | // In this example, this does not happen, but you can do that to gracefully
120 | // shut down your server.
121 | f.channel().closeFuture().sync(); // 9
122 | } catch (Exception e) {
123 | Log.e(TAG, e.getLocalizedMessage());
124 | e.printStackTrace();
125 | } finally {
126 | isServerStart = false;
127 | listener.onStopServer();
128 | workerGroup.shutdownGracefully();
129 | bossGroup.shutdownGracefully();
130 | }
131 | }
132 |
133 | public void disconnect() {
134 | workerGroup.shutdownGracefully();
135 | bossGroup.shutdownGracefully();
136 | }
137 |
138 | public void setListener(NettyListener listener) {
139 | this.listener = listener;
140 | }
141 |
142 | public void setConnectStatus(boolean connectStatus) {
143 | this.connectStatus = connectStatus;
144 | }
145 |
146 | public boolean getConnectStatus() {
147 | return connectStatus;
148 | }
149 |
150 | public boolean isServerStart(){
151 | return isServerStart;
152 | }
153 |
154 |
155 | public boolean sendMsgToServer(String data, ChannelFutureListener listener) {
156 | boolean flag = channel != null && connectStatus && channel.isActive();
157 | if (flag) {
158 | // ByteBuf buf = Unpooled.copiedBuffer(data);
159 | // ByteBuf byteBuf = Unpooled.copiedBuffer(data + System.getProperty("line.separator"), //2
160 | // CharsetUtil.UTF_8);
161 | channel.writeAndFlush(data + System.getProperty("line.separator")).addListener(listener);
162 | }
163 | return flag;
164 | }
165 |
166 | public void setChannel(Channel channel) {
167 | this.channel = channel;
168 | }
169 |
170 |
171 | // @Override
172 | // public void onMessageResponse(Channel channel,Object msg) {
173 | // // TODO Auto-generated method stub
174 | // this.channel = channel;
175 | //// ByteBuf in = (ByteBuf) msg;
176 | // System.out.println("Server received: " + msg); //2
177 | // }
178 | //
179 | // @Override
180 | // public void onServiceStatusConnectChanged(int statusCode) {
181 | // // TODO Auto-generated method stub
182 | //
183 | // }
184 | }
185 |
--------------------------------------------------------------------------------
/nettyserver/src/main/java/ifreecomm/nettyserver/EchoServerHandler.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettyserver;
2 |
3 | import android.util.Log;
4 |
5 | import io.netty.channel.ChannelHandler;
6 | import io.netty.channel.ChannelHandlerContext;
7 | import io.netty.channel.SimpleChannelInboundHandler;
8 |
9 |
10 | @ChannelHandler.Sharable //1
11 | public class EchoServerHandler extends SimpleChannelInboundHandler {
12 |
13 | private static final String TAG = "EchoServerHandler";
14 | private NettyListener mListener;
15 |
16 | public EchoServerHandler(NettyListener listener) {
17 | this.mListener = listener;
18 | }
19 |
20 | /* @Override
21 | public void channelRead(ChannelHandlerContext ctx,
22 | Object msg) {
23 |
24 |
25 | // ctx.write(in);
26 | // ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(in.toString(Charset.forName("GBK"))+System.getProperty("line.separator"),
27 | // Charset.forName("GBK")));//3
28 | // ctx.channel().writeAndFlush(HEARTBEAT_SEQUENCE);
29 | }*/
30 |
31 | @Override
32 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
33 | // System.out.println("channelReadComplete");
34 | // ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)//4
35 | // .addListener(ChannelFutureListener.CLOSE);
36 | }
37 |
38 | @Override
39 | public void exceptionCaught(ChannelHandlerContext ctx,
40 | Throwable cause) {
41 | cause.printStackTrace(); //5
42 | ctx.close(); //6
43 | }
44 |
45 | @Override
46 | protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
47 | mListener.onMessageResponse(msg);
48 | }
49 |
50 | /**
51 | * 连接成功
52 | *
53 | * @param ctx
54 | * @throws Exception
55 | */
56 | @Override
57 | public void channelActive(ChannelHandlerContext ctx) throws Exception {
58 | Log.e(TAG, "channelActive");
59 | mListener.onChannel(ctx.channel());
60 | EchoServer.getInstance().setConnectStatus(true);
61 | mListener.onServiceStatusConnectChanged(NettyListener.STATUS_CONNECT_SUCCESS);
62 | }
63 |
64 | @Override
65 | public void channelInactive(ChannelHandlerContext ctx) throws Exception {
66 | Log.e(TAG, "channelInactive");
67 | EchoServer.getInstance().setConnectStatus(false);
68 | mListener.onServiceStatusConnectChanged(NettyListener.STATUS_CONNECT_CLOSED);
69 | // NettyClient.getInstance().reconnect();
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/nettyserver/src/main/java/ifreecomm/nettyserver/MainActivity.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettyserver;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.support.v7.widget.LinearLayoutManager;
6 | import android.support.v7.widget.RecyclerView;
7 | import android.text.TextUtils;
8 | import android.util.Log;
9 | import android.view.View;
10 | import android.widget.Button;
11 | import android.widget.EditText;
12 | import android.widget.TextView;
13 | import android.widget.Toast;
14 |
15 | import ifreecomm.nettyserver.adapter.LogAdapter;
16 | import ifreecomm.nettyserver.bean.LogBean;
17 | import io.netty.channel.Channel;
18 | import io.netty.channel.ChannelFuture;
19 | import io.netty.channel.ChannelFutureListener;
20 |
21 | import static android.widget.Toast.LENGTH_SHORT;
22 |
23 | public class MainActivity extends AppCompatActivity implements View.OnClickListener, NettyListener {
24 |
25 | private static final String TAG = "MainActivity";
26 | private Button mClearLog;
27 | private Button mSendBtn;
28 | private Button startServer;
29 | private EditText mSendET;
30 | private RecyclerView mSendList;
31 | private RecyclerView mReceList;
32 |
33 | private LogAdapter mSendLogAdapter = new LogAdapter();
34 | private LogAdapter mReceLogAdapter = new LogAdapter();
35 | private TextView receiveTv;
36 |
37 | @Override
38 | protected void onCreate(Bundle savedInstanceState) {
39 | super.onCreate(savedInstanceState);
40 | setContentView(R.layout.activity_main);
41 |
42 | findViews();
43 | initData();
44 | initlistener();
45 | }
46 |
47 | private void initlistener() {
48 | }
49 |
50 |
51 |
52 | private void initData() {
53 | LinearLayoutManager manager1 = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
54 | mSendList.setLayoutManager(manager1);
55 | mSendList.setAdapter(mSendLogAdapter);
56 |
57 | LinearLayoutManager manager2 = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
58 | mReceList.setLayoutManager(manager2);
59 | mReceList.setAdapter(mReceLogAdapter);
60 |
61 | }
62 |
63 | private void findViews() {
64 | mSendList = findViewById(R.id.send_list);
65 | mReceList = findViewById(R.id.rece_list);
66 | mSendET = findViewById(R.id.send_et);
67 | mSendBtn = findViewById(R.id.send_btn);
68 | mClearLog = findViewById(R.id.clear_log);
69 | startServer = findViewById(R.id.startServer);
70 | receiveTv = findViewById(R.id.receiveTv);
71 |
72 | startServer.setOnClickListener(this);
73 | mSendBtn.setOnClickListener(this);
74 | mClearLog.setOnClickListener(this);
75 | }
76 |
77 | @Override
78 | public void onClick(View v) {
79 | switch (v.getId()) {
80 |
81 | case R.id.startServer:
82 |
83 | startServer();
84 |
85 | break;
86 |
87 | case R.id.send_btn:
88 | if (!EchoServer.getInstance().getConnectStatus()) {
89 | Toast.makeText(getApplicationContext(), "未连接,请先连接", LENGTH_SHORT).show();
90 | } else {
91 | final String msg = mSendET.getText().toString();
92 | if (TextUtils.isEmpty(msg.trim())) {
93 | return;
94 | }
95 | EchoServer.getInstance().sendMsgToServer(msg, new ChannelFutureListener() {
96 | @Override
97 | public void operationComplete(ChannelFuture channelFuture) throws Exception {
98 | if (channelFuture.isSuccess()) { //4
99 | Log.d(TAG, "Write auth successful");
100 | logSend(msg);
101 | } else {
102 | Log.d(TAG, "Write auth error");
103 | }
104 | }
105 | });
106 | mSendET.setText("");
107 | }
108 | break;
109 |
110 | case R.id.clear_log:
111 | mReceLogAdapter.getDataList().clear();
112 | mSendLogAdapter.getDataList().clear();
113 | mReceLogAdapter.notifyDataSetChanged();
114 | mSendLogAdapter.notifyDataSetChanged();
115 | break;
116 | }
117 | }
118 |
119 | private void startServer() {
120 |
121 | if(!EchoServer.getInstance().isServerStart()){
122 | new Thread(new Runnable() {
123 | @Override
124 | public void run() {
125 | EchoServer.getInstance().setListener(MainActivity.this);
126 | EchoServer.getInstance().start();
127 | }
128 | }).start();
129 |
130 | }else{
131 | EchoServer.getInstance().disconnect();
132 | }
133 | }
134 |
135 | @Override
136 | public void onMessageResponse(Object msg) {
137 | // TODO Auto-generated method stub
138 |
139 | // ByteBuf in = (ByteBuf) msg;
140 | System.out.println("Server received: " + msg); // 2
141 | logRece((String) msg);
142 | }
143 | @Override
144 | public void onChannel(final Channel channel) {
145 | EchoServer.getInstance().setChannel(channel);
146 | runOnUiThread(new Runnable() {
147 | @Override
148 | public void run() {
149 | receiveTv.setText("接收("+channel.toString()+")");
150 | }
151 | });
152 |
153 | }
154 |
155 | @Override
156 | public void onStartServer() {
157 | runOnUiThread(new Runnable() {
158 | @Override
159 | public void run() {
160 | startServer.setText("stopServer");
161 | }
162 | });
163 | }
164 |
165 | @Override
166 | public void onStopServer() {
167 | runOnUiThread(new Runnable() {
168 | @Override
169 | public void run() {
170 | startServer.setText("startServer");
171 | }
172 | });
173 |
174 | }
175 |
176 | @Override
177 | public void onServiceStatusConnectChanged(final int statusCode) {
178 | runOnUiThread(new Runnable() {
179 | @Override
180 | public void run() {
181 | if (statusCode == NettyListener.STATUS_CONNECT_SUCCESS) {
182 | Log.e(TAG, "STATUS_CONNECT_SUCCESS:");
183 | } else {
184 | Log.e(TAG, "onServiceStatusConnectChanged:" + statusCode);
185 | receiveTv.setText("接收");
186 | }
187 | }
188 | });
189 | }
190 |
191 | private void logSend(String log) {
192 | LogBean logBean = new LogBean(System.currentTimeMillis(), log);
193 | mSendLogAdapter.getDataList().add(0, logBean);
194 | runOnUiThread(new Runnable() {
195 | @Override
196 | public void run() {
197 | mSendLogAdapter.notifyDataSetChanged();
198 | }
199 | });
200 |
201 | }
202 |
203 | private void logRece(String log) {
204 | LogBean logBean = new LogBean(System.currentTimeMillis(), log);
205 | mReceLogAdapter.getDataList().add(0, logBean);
206 | runOnUiThread(new Runnable() {
207 | @Override
208 | public void run() {
209 | mReceLogAdapter.notifyDataSetChanged();
210 | }
211 | });
212 |
213 | }
214 |
215 | }
216 |
--------------------------------------------------------------------------------
/nettyserver/src/main/java/ifreecomm/nettyserver/NettyListener.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettyserver;
2 |
3 |
4 | import io.netty.channel.Channel;
5 |
6 |
7 | public interface NettyListener {
8 |
9 | public final static byte STATUS_CONNECT_SUCCESS = 1;
10 |
11 | public final static byte STATUS_CONNECT_CLOSED = 0;
12 |
13 | public final static byte STATUS_CONNECT_ERROR = 0;
14 |
15 |
16 | void onMessageResponse(Object msg);
17 |
18 | /**
19 | * 与客户端建立连接
20 | * @param channel
21 | */
22 | void onChannel(Channel channel);
23 |
24 | void onStartServer();
25 | void onStopServer();
26 |
27 |
28 | public void onServiceStatusConnectChanged(int statusCode);
29 | }
30 |
--------------------------------------------------------------------------------
/nettyserver/src/main/java/ifreecomm/nettyserver/adapter/LogAdapter.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettyserver.adapter;
2 |
3 | import android.content.ClipData;
4 | import android.content.ClipboardManager;
5 | import android.content.Context;
6 | import android.support.v7.widget.RecyclerView;
7 | import android.view.LayoutInflater;
8 | import android.view.View;
9 | import android.view.ViewGroup;
10 | import android.widget.TextView;
11 | import android.widget.Toast;
12 |
13 | import java.util.ArrayList;
14 | import java.util.List;
15 |
16 | import ifreecomm.nettyserver.R;
17 | import ifreecomm.nettyserver.bean.LogBean;
18 |
19 |
20 | public class LogAdapter extends RecyclerView.Adapter {
21 |
22 | private List mDataList = new ArrayList<>();
23 |
24 | @Override
25 | public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
26 | return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.log_item, parent, false));
27 | }
28 |
29 | @Override
30 | public void onBindViewHolder(final ItemHolder holder, int position) {
31 | LogBean bean = mDataList.get(position);
32 |
33 | holder.mTime.setText(bean.mTime);
34 | holder.mLog.setText(bean.mLog);
35 |
36 | holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
37 | @Override
38 | public boolean onLongClick(View v) {
39 | ClipboardManager cmb = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
40 | LogBean log = mDataList.get(holder.getAdapterPosition());
41 | String msg = log.mTime + " " + log.mLog;
42 | cmb.setPrimaryClip(ClipData.newPlainText(null, msg));
43 | Toast.makeText(v.getContext(), "已复制到剪贴板", Toast.LENGTH_LONG).show();
44 | return true;
45 | }
46 | });
47 | }
48 |
49 | @Override
50 | public int getItemCount() {
51 | return mDataList.size();
52 | }
53 |
54 | public class ItemHolder extends RecyclerView.ViewHolder {
55 | public TextView mTime;
56 | public TextView mLog;
57 |
58 | public ItemHolder(View itemView) {
59 | super(itemView);
60 | mTime = (TextView) itemView.findViewById(R.id.time);
61 | mLog = (TextView) itemView.findViewById(R.id.logtext);
62 | }
63 | }
64 |
65 | public List getDataList() {
66 | return mDataList;
67 | }
68 | }
--------------------------------------------------------------------------------
/nettyserver/src/main/java/ifreecomm/nettyserver/bean/LogBean.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettyserver.bean;
2 |
3 | import java.text.SimpleDateFormat;
4 |
5 | public class LogBean {
6 | public String mTime;
7 | public String mLog;
8 |
9 | public LogBean(long time, String log) {
10 | SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
11 | mTime = format.format(time);
12 | mLog = log;
13 | }
14 | }
--------------------------------------------------------------------------------
/nettyserver/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/nettyserver/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/nettyserver/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
12 |
13 |
17 |
18 |
19 |
23 |
24 |
29 |
30 |
37 |
38 |
43 |
44 |
48 |
49 |
58 |
59 |
67 |
68 |
69 |
70 |
74 |
75 |
84 |
85 |
91 |
92 |
93 |
94 |
95 |
96 |
--------------------------------------------------------------------------------
/nettyserver/src/main/res/layout/log_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
13 |
14 |
20 |
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/nettyserver/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/nettyserver/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/nettyserver/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/nettyserver/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/nettyserver/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/nettyserver/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/nettyserver/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/nettyserver/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/nettyserver/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/nettyserver/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/nettyserver/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/nettyserver/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/nettyserver/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | NettyServer
3 |
4 |
--------------------------------------------------------------------------------
/nettyserver/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/nettyserver/src/test/java/ifreecomm/nettyserver/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package ifreecomm.nettyserver;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/screenshot/clent.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/screenshot/clent.gif
--------------------------------------------------------------------------------
/screenshot/server.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thisfeng/NettyDemo/b03a6216bca923d6c13ab157aa8833abf58f279c/screenshot/server.gif
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':nettyserver'
2 |
--------------------------------------------------------------------------------