WEB开发网
开发学院手机开发Android 开发 Android socket编程 以非阻塞I/O服务器及Service为... 阅读

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);Stri

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();

}

}

上一页  1 2 3 4 5 6  下一页

Tags:Android socket 编程

编辑录入:coldstar [复制链接] [打 印]
赞助商链接