Android socket编程 以非阻塞I/O服务器及Service为例
2010-08-22 04:49:00 来源:WEB开发网源代码如下:
Server端:
package com.android.Yao;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.nio.charset.*;
import java.lang.*;
public class YaoChatServer
{
public Selector sel = null;
public ServerSocketChannel server = null;
public SocketChannel socket = null;
public int thisport = 4900;
private String result = null;
private Hashtable
private SocketChannel readingsocket = null;
public YaoChatServer()
{
System.out.println("Inside startserver ");
}
public YaoChatServer(int port)
{
System.out.println("Inside startserver ");
thisport = port;
}
public void initializeOperations() throws IOException,UnknownHostException
{
System.out.println("Inside initialization ");
sel = Selector.open();
server = ServerSocketChannel.open();
server.configureBlocking(false);
InetAddress ia = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(ia,thisport);
server.socket().bind(isa);
userlists = new Hashtable
}
public void startServer() throws IOException
{
initializeOperations();
server.register(sel, SelectionKey.OP_ACCEPT);
while (sel.select() > 0 )
{
Set readyKeys = sel.selectedKeys();
Iterator it = readyKeys.iterator();
while(it.hasNext())
{
SelectionKey key = (SelectionKey)it.next();
it.remove();
更多精彩
赞助商链接