参考了:https://blog.csdn.net/yulinxx/article/details/51085782
首先服务器使用Netty框架搭建,关于Netty环境的搭建参考Netty环境搭建(Eclipse)
Android客户端也采用了Netty框架,环境搭建参考Android作为客户端Netty环境搭建
注意:1,Android端的Netty版本需要与服务器的Netty版本一致
2,Android端需要一些权限
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
一,服务器端代码如下
1,Server.java
package com.server.androidTest;
import javax.sound.sampled.Port;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class Server {
private int port = 8080;
public Server(int port) {
this.port = port;
}
public void start() {
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss,worker)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new SimpleInitializer());
ChannelFuture future = bootstrap.bind(this.port).sync();
System.out.println("服务器已经启动");
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
public static void main(String[] args){
// TODO Auto-generated method stub
new Server(8080).start();
}
}
2,SimpleInitializer.java
package com.server.androidTest;
import java.beans.Encoder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class SimpleInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// TODO Auto-generated method stub
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("framer",new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()))
.addLast("decoder",new StringDecoder())
.addLast("encoder",new StringEncoder())
.addLast("handler",new ServerHandler());
}
}
3,ServerHandler.java
package com.server.androidTest;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
public class ServerHandler extends SimpleChannelInboundHandler<String>{
/**
* A thread-safe Set Using ChannelGroup, you can categorize Channels into a meaningful group.
* A closed Channel is automatically removed from the collection,
*/
private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
Channel channel = ctx.channel();
System.out.println("Client :"+channel.remoteAddress()+" 在线\n");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
Channel channel = ctx.channel();
System.out.println("Client :"+channel.remoteAddress()+" 离线\n");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
Channel channel = ctx.channel();
System.out.println("Client :"+channel.remoteAddress()+" 异常\n");
cause.printStackTrace();
ctx.close();
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
Channel channel = ctx.channel();
System.out.println("-------handlerAdded");
channels.writeAndFlush("[Server]: "+channel.remoteAddress()+" 加入\n");
channels.add(channel);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
Channel channel = ctx.channel();
System.out.println("-------handlerRemoved");
channels.writeAndFlush("[Server]: "+channel.remoteAddress()+" 离开\n");
// A closed Channel is automatically removed from ChannelGroup,
// so there is no need to do "channels.remove(ctx.channel());"
channels.remove(channel);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
// TODO Auto-generated method stub
System.out.println("---channelRead0 hava received");
Channel inComing = ctx.channel();
for(Channel channel:channels) {
if(channel!=inComing) {
channel.writeAndFlush("["+inComing.remoteAddress()+"]: "+msg+"\n");
}else {
channel.writeAndFlush("[localhost]: "+msg+"\n");
}
}
}
}
二,Android客户端
1,MainActivity.java
package com.example.ffy.other;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Client client = new Client();
client.start();
}
}
2, Client,java
package com.example.ffy.other;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* Created by ffy on 19-1-21.
*/
public class Client extends Thread{
public static String host = "192.168.43.102";
public static int port = 8080;
public void run(){
super.run();
EventLoopGroup worker = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap()
.group(worker)
.channel(NioSocketChannel.class)
.handler(new ClientInitializer());
Channel channel = bootstrap.connect(host, port).sync().channel();
while(true){
channel.writeAndFlush("this msg test come from client" + "\r\n");
Thread.currentThread();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
worker.shutdownGracefully();
}
}
}
3, ClientInitializer.java
package com.example.ffy.other;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
* Created by ffy on 19-1-21.
*/
class ClientInitializer extends ChannelInitializer {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("framer",new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder",new StringDecoder());
pipeline.addLast("eencoder",new StringEncoder());
pipeline.addLast("handler",new ClientHandler());
}
}
4, ClientHandler.java
package com.example.ffy.other;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* Created by ffy on 19-1-21.
*/
class ClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("[Server]: "+msg);
}
}