Android socket编程 以非阻塞I/O服务器及Service为例
2010-08-22 04:49:00 来源:WEB开发网}
public String readMessage(SocketChannel sc)
{
int nBytes = 0;
ByteBuffer buf = ByteBuffer.allocate(1024);
try {
nBytes = sc.read(buf);
buf.flip();
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buf);
result = charBuffer.toString();
} catch (IOException e) {
result = "@@@@@ is going to say goodbye!";
}
return result;
}
public static void main(String args[])
{
YaoChatServer nb = new YaoChatServer();
try
{
nb.startServer();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(-1);
}
}
}
Android客户端的Service类:
package com.android.Yao;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Collection;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class ReceiveMessage extends Service{
private SocketChannel client = null;
private InetSocketAddress isa = null;
更多精彩
赞助商链接