[Android初级]android与netty4初体验

    博主曾经对netty4的helloword很感兴趣,也曾单纯的写过一个小小的聊天室java代码,现在重新来看看,浏览了这位牛人的博客 点击去看看

    我觉得受益匪浅,故拿来分享。

     这次是在android上使用netty作为客户端,来与服务端相互通讯的小事例,纯粹的helloworld,效果就是在android程序中发送一个消息到服务端,然后服务端也回一个消息给客户端,很简单的demo,.大牛看了可不要吐槽啊!

1.demo结构

技术分享

2.服务端代码:

Server.java

package org.jan.netty.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class MyHelloServer {

	private static final int PORT = 7878;

	public static void main(String[] args) {
		EventLoopGroup parentGroup = new NioEventLoopGroup();
		EventLoopGroup childrenGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(parentGroup, childrenGroup);
			serverBootstrap.channel(NioServerSocketChannel.class);
			//添加工作线程
			serverBootstrap.childHandler(new MyHelloServerInitializer());
			// 服务器绑定端口监听
			ChannelFuture cf = serverBootstrap.bind(PORT).sync();
			// 监听服务器关闭监听
			cf.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			parentGroup.shutdownGracefully();
			childrenGroup.shutdownGracefully();
		}
	}
}

MyHelloServerHandler.java

package org.jan.netty.demo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetAddress;
import java.nio.charset.Charset;

public class MyHelloServerHanler extends SimpleChannelInboundHandler<String> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg)
			throws Exception {
		String recStr = new String(msg.getBytes(), Charset.forName("UTF-8"));
		//收到消息直接打印输出
		System.out.println(ctx.channel().remoteAddress()+" say :"+recStr);
		//返回客户端 
		ctx.writeAndFlush("Received your message!\n");
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("RamoteAddress: "+ctx.channel().remoteAddress()+" active!");
//		ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName() + "'s service!\n");
		ctx.writeAndFlush("我是服务端,我是服务端!\n");
		super.channelActive(ctx);
	}
}



3.android客户端代码:

package org.jan.nio.exapmle;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ClientActivity extends Activity {
	private static final String TAG = "MainActivity";
	public static final String HOST = "192.168.50.110";
	public static int PORT = 7878;
	private NioEventLoopGroup group;
	private Button sendButton;
	private static Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = this;
		sendButton = (Button) findViewById(R.id.netty_send_button);
		sendButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				connected();
			}
		});
	}

	// 连接到Socket服务端
	private void connected() {
		new Thread() {
			@Override
			public void run() {
				 group = new NioEventLoopGroup();
				try {
					// Client服务启动器 3.x的ClientBootstrap
					// 改为Bootstrap,且构造函数变化很大,这里用无参构造。
					Bootstrap bootstrap = new Bootstrap();
					// 指定channel类型
					bootstrap.channel(NioSocketChannel.class);
					// 指定Handler
					bootstrap.handler(new MyClientInitializer(context));
					// 指定EventLoopGroup
					bootstrap.group(group);
					// 连接到目标IP的8000端口的服务端
					Channel channel = bootstrap.connect(new InetSocketAddress(HOST,
											PORT)).sync().channel();
					channel.writeAndFlush("我是客户端,我是客户端!\r\n");
					channel.read();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

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

4.实现效果:

技术分享

去下载demo

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。