//Java NIO (異步IO)Socket通信例子:
服務器代碼:
import
import java
import java
import java
public class server
{
ServerSocketChannel ssc ;
public void start()
{
try
{
Selector selector = Selector
ServerSocketChannel ssc=ServerSocketChannel
nfigureBlocking(false);
ServerSocket ss=ssc
InetSocketAddress address = new InetSocketAddress(
ss
ssc
System
while(true)
{
selector
Set<SelectionKey> selectionKeys=selector
Iterator<SelectionKey> iter=erator();
ByteBuffer echoBuffer=ByteBuffer
SocketChannel sc;
while(iter
{
SelectionKey key=iter
if((key
{
ServerSocketChannel subssc=(ServerSocketChannel)key
sc=subssc
nfigureBlocking(false);
sc
iter
System
}
else if((key
{
sc=(SocketChannel) key
while(true)
{
echoBuffer
int a;
try
{
a=sc
}
catch(Exception e)
{
e
break;
}
if(a==
if(a>
{
byte[] b=echoBuffer
System
echoBuffer
sc
System
}
}
sc
System
System
iter
}
}
}
}
catch (Exception e)
{
e
}
}
}
客戶端代碼:
import
import java
import java
public class client
{
public void start()
{
try
{
SocketAddress address = new InetSocketAddress(
SocketChannel client=SocketChannel
nfigureBlocking(false);
String a=
ByteBuffer buffer=ByteBuffer
buffer
buffer
int d=client
System
while(true)
{
buffer
int i=client
if(i>
{
byte[] b=buffer
System
client
System
break;
}
}
}
catch(Exception e)
{
e
}
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25874.html