android netty5局域网通讯(客户端+服务端)

                                          这是一个WebSocket协议的Demo,仅仅粗略的实现了功能

       WebSocket是HTML5开始提供的一种浏览器与服务器建进行全双工通讯的网络协议,它的出现是为了解决HTTP协议效率低下的问题,WebSocket能更好的节省服务器资源和带宽并达到实时通信!


Demo下载


Client:

package com.tomorrow_p.netty_p;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
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.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class ClientActivity extends AppCompatActivity {
    public static Context mContext;
    public static int WHAT = 0xabc;
    public static int PORT = 7815;
    public static final String HOST = "127.0.0.1";
    //    public static final String HOST = "192.168.199.117";
    private NioEventLoopGroup group;
    private Channel mChannel;
    private ChannelFuture cf;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == WHAT) {
                Toast.makeText(mContext, msg.obj.toString(), Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        //服务端
        startService(new Intent(this, ServiceService.class));
        //客户端
        connected();

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }
        });
    }

    // 连接到Socket服务端
    private void connected() {
        new Thread() {
            @Override
            public void run() {
                group = new NioEventLoopGroup();
                try {
                    Bootstrap bootstrap = new Bootstrap();

                    bootstrap.group(group);

                    bootstrap.channel(NioSocketChannel.class);

                    bootstrap.handler(new ChannelInitializer() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                            pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                            pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));

                            pipeline.addLast("handler", new SimpleChannelInboundHandler() {
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    super.channelActive(ctx);
                                }

                                @Override
                                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                    super.channelInactive(ctx);
                                }

                                @Override
                                protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
                                    Message m = new Message();
                                    m.what = ClientActivity.WHAT;
                                    m.obj = msg;
                                    mHandler.sendMessage(m);
                                }
                            });
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg)
                                throws Exception {
                            super.channelRead(ctx, msg);
                        }

                        @Override
                        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                            super.channelReadComplete(ctx);
                        }

                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            super.channelActive(ctx);
                        }
                    });
                    mChannel = bootstrap.connect(HOST, PORT).sync().channel();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void sendMessage() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                try {

                    mChannel.writeAndFlush("Client  >>  Service\n");
                    mChannel.read();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (group != null) {
            group.shutdownGracefully();
        }
    }

}

Service:
package com.tomorrow_p.netty_p;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.net.InetAddress;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
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 ansen on 2015/2/5.
 */
public class ServiceService extends Service {

    private static final int PORT = 7815;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        new Thread(new Runnable() {
            @Override
            public void run() {
                EventLoopGroup parentGroup = new NioEventLoopGroup();
                EventLoopGroup childrenGroup = new NioEventLoopGroup();
                try {
                    ServerBootstrap serverBootstrap = new ServerBootstrap();
                    serverBootstrap.group(parentGroup, childrenGroup);
                    serverBootstrap.channel(NioServerSocketChannel.class);

                    serverBootstrap.childHandler(new 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("encoder", new StringEncoder());

                            pipeline.addLast("handler", new SimpleChannelInboundHandler() {

                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {

                                    Log.d("ansen", "service:   " + InetAddress.getLocalHost().getHostName() + "   start");

                                    ctx.writeAndFlush("service:   " + InetAddress.getLocalHost().getHostName() + "   start\n");

                                    super.channelActive(ctx);
                                }

                                @Override
                                protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {

                                    Log.d("ansen", "remoteAddress: "+ctx.channel().remoteAddress() + "   msg : " + msg);

                                    ctx.writeAndFlush("msg:  "+msg+"    service received \n");
                                }
                            });
                        }
                    });

                    ChannelFuture cf = serverBootstrap.bind(PORT).sync();

                    cf.channel().closeFuture().sync();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    parentGroup.shutdownGracefully();
                    childrenGroup.shutdownGracefully();
                }
            }
        }).start();


    }
}



你可能感兴趣的:(Android,#,Basic,android,studio,快捷键)