android netty 5ローカルエリアネットワーク通信(クライアント+サービス側)
これはWebSocketプロトコルのDemoで、ざっと機能を実現しただけです.
WebSocketはHTML 5が提供し始めたブラウザとサーバがフルデュプレクス通信を行うネットワークプロトコルで、HTTPプロトコルの効率が低下する問題を解決するために登場し、WebSocketはサーバリソースと帯域幅をよりよく節約し、リアルタイム通信を実現することができます.
Demoダウンロード
Client:
Service:
WebSocketはHTML 5が提供し始めたブラウザとサーバがフルデュプレクス通信を行うネットワークプロトコルで、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
");
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
");
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
");
}
});
}
});
ChannelFuture cf = serverBootstrap.bind(PORT).sync();
cf.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
parentGroup.shutdownGracefully();
childrenGroup.shutdownGracefully();
}
}
}).start();
}
}