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

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

源代码如下:

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 userlists ;

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

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

Tags:Android socket 编程

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