Android socket编程 以非阻塞I/O服务器及Service为例
2010-08-22 04:49:00 来源:WEB开发网private String message="";
public void onCreate() {
super.onCreate();
ConnectToServer();
StartServerListener();
}
public void onDestroy() {
super.onDestroy();
DisConnectToServer();
}
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
/*
* IBinder方法 , LocalBinder 类,mBinder接口这三项用于
* Activity进行Service的绑定,点击发送消息按钮之后触发绑定
* 并通过Intent将Activity中的EditText的值
* 传送到Service中向服务器发送
*
* */
public IBinder onBind(Intent intent) {
message = intent.getStringExtra("chatmessage");
if(message.length()>0)
{
SendMessageToServer(message);
}
return mBinder;
}
public class LocalBinder extends Binder {
ReceiveMessage getService() {
return ReceiveMessage.this;
}
}
private final IBinder mBinder = new LocalBinder();
//用于链接服务器端
public void ConnectToServer()
{
try {
client = SocketChannel.open();
isa = new InetSocketAddress("192.168.0.107",4900);
client.connect(isa);
client.configureBlocking(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//断开与服务器端的链接
public void DisConnectToServer()
{
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//启动服务器端的监听线程,从Server端接收消息
public void StartServerListener()
更多精彩
赞助商链接