Android socket编程 以非阻塞I/O服务器及Service为例
2010-08-22 04:49:00 来源:WEB开发网if (key.isAcceptable())
{
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
socket = (SocketChannel) ssc.accept();
socket.configureBlocking(false);
String socketname = socket.socket().getRemoteSocketAddress().toString();
socket.register(sel, SelectionKey.OP_WRITE);
userlists.put(socketname,socket);
System.out.println(socketname +" is connected!");
}
if (key.isWritable()) {
readingsocket =(SocketChannel)key.channel();
String ret=readMessage(readingsocket);
if (ret.equalsIgnoreCase("@@@@@ is going to say goodbye!"))
{
key.cancel();
readingsocket.close();
userlists.remove(readingsocket.socket().getRemoteSocketAddress().toString());
System.out.println("send server msg:"+ret.replace("@@@@@", readingsocket.socket().getRemoteSocketAddress().toString()));
sendMessage(ret.replace("@@@@@", readingsocket.socket().getRemoteSocketAddress().toString()));
}
else if (ret.length() > 0 ) {
System.out.println("send server msg:"+ret);
sendMessage(ret);
}
}
}
}
}
public void sendMessage(String msg) throws IOException
{
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer = ByteBuffer.wrap(msg.getBytes());
// ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes("UTF-8"));
Collection channels = userlists.values();
SocketChannel sc;
for(Object o:channels){
sc = (SocketChannel)o;
sc.write(buffer);
buffer.flip();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
更多精彩
赞助商链接