Android与Netty服务器连接

转载https://blog.csdn.net/qq_37437983/article/details/86585079
服务端:
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");
			}
		}
	}
		
}

安卓端:

1.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;
 

 
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();
        }
    }
 
}

2.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;
 

 
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());
    }
}

3.ClientHandler.java

package com.example.ffy.other;
 
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
 

 
class ClientHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("[Server]: "+msg);
    }
}

之前试过用java原生的Socket去测试,本地是可以的,但是我部署到服务器之后来回传递消息延迟非常,后来发现是CPU占了99%,通过打印服务器日志发现,是一直处于等待、监听状态,所以导致占CPU很大,我也是个菜鸟,后来知道是需要释放资源的,后来去找了socket的框架,找到了netty可以使用,只不过可能netty水会深一点吧,毕竟对于一个没有多少开发经验的小白来说。起码netty我部署到1c1g的服务器是占cpu很低,速度很快的。
后来阅读文章看到阿里也有对netty封装过的框架,名字好像是叫SOFABolt
git地址:https://github.com/alipay/sofa-bolt
如有说的不对的地方,请各位大佬指正,相互学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值