Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> [Android初級]android與netty4初體驗

[Android初級]android與netty4初體驗

編輯:關於Android編程

博主曾經對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 {

	@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!
);
	}

	@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!
);
		ctx.writeAndFlush(我是服務端,我是服務端!
);
		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(我是客戶端,我是客戶端!
);
					channel.read();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

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

4.實現效果:

 

\

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved