嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元微信扫码支付:2 元
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
adroid netty自己写的简单例子
package com.txn.day3;
import java.net.InetSocketAddress;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
public class ClientActivity extends Activity {
private static final String TAG = "MainActivity";
private static Context context;
//0x开头表示十六进制的数值
public static int MSG_REC = 0xabc;
public static int PORT = 9090;
public static final String HOST = "172.16.2.44";
private NioEventLoopGroup group;
private ChannelFuture cf;
private Channel mChannel;
private Button sendButton;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == MSG_REC) {
Toast.makeText(context, msg.obj.toString(), 1000).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
connected();
sendButton = (Button) findViewById(R.id.netty_send_button);
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
}
// 连接到Socket服务端
private void connected() {
new Thread() {
@Override
public void run() {
group = new NioEventLoopGroup();
try {
// 创建Bootstrap,且构造函数变化很大,这里用无参构造。
Bootstrap bootstrap = new Bootstrap();
// 指定EventLoopGroup
bootstrap.group(group);
// 指定channel类型
bootstrap.channel(NioSocketChannel.class);
// 指定Handler
bootstrap.handler(new MyClientInitializer(context, mHandler));
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
cf = bootstrap.connect(new InetSocketAddress(HOST, PORT));
mChannel = cf.sync().channel();
} catch (Exception e) {
Log.i("main", e.toString());
}
}
}.start();
}
// 发送数据
private void sendMessage() {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
// Log.i(TAG, "mChannel.write sth & " mChannel.isOpen());
mChannel.writeAndFlush("hello,this message is from client.\r\n");
mChannel.read();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (group != null) {
group.shutdownGracefully();
}
}
}