使用nio写简单的完成简单的收发数据功能所得

来源:互联网 发布:cf领枪软件 编辑:程序博客网 时间:2024/06/05 00:59

1. ByteBuffer 初用该类还是有点坑, 比如用ByteBuffer的put方法后,需要通过flip函数调整position和limit,只有这样才能保证put进去的内容,被后面得代码所得。例如:

ByteBuffer bb = ByteBuffer.allocate(128);

bb.put(new String("server  write-----------").getBytes());

bb.flip();

((ByteChannel)(e.channel())).write(bb);   


如果没有这里的flip(), 则不会将 put的内容写入到套接字中

2. SelectionKey.OP_WRITE, 对于连接成功的新套接字,注册到Selector时,只要使用SelectionKey.OP_READ选项而不要使用SelectionKey.OP_WRITE选项,如果使用了后者,则Select()检测时每次都会检测到该套接字。


3. 简单的client、server代码

public class Client {


public static void main(String[] args) {
SocketChannel sc = null;
try {
sc = SocketChannel.open();

if (sc.connect(new InetSocketAddress(10009)) ) {
sc.socket().setTcpNoDelay(true);
String str = new String("client");
byte[] bs = str.getBytes();
ByteBuffer bb = ByteBuffer.allocate(16);
bb.put(bs);
bb.flip();
int n = ((ByteChannel)sc).write(bb);
System.out.println(n);

bb.clear();
int rn = ((ByteChannel)sc).read(bb);
System.out.println("Client read rn = " + rn);
bb.flip();

byte[] bb1 = new byte[bb.remaining()];
bb.get(bb1, 0, bb1.length);
System.out.println("received : " + new String(bb1));

try {
Thread.currentThread().sleep(60000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (sc != null)
try {
sc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}


}


=============================================================================================================

public class Server {


public static void main(String[] args) {
try {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.bind(new InetSocketAddress(10009));
ssc.configureBlocking(false);
ssc.socket().setReuseAddress(true);

Selector sel = Selector.open();
ssc.register(sel, SelectionKey.OP_ACCEPT);

while (true) {
int n = sel.select();
if (n < 0)
continue;

for (SelectionKey e : sel.selectedKeys()) {
if (!e.isValid())
continue;

if (e.isAcceptable()) {
SocketChannel sc = ((ServerSocketChannel)(e.channel())).accept();
if (sc != null) {
sc.socket().setTcpNoDelay(true);
sc.socket().setReceiveBufferSize(1024);
sc.configureBlocking(false);

sc.register(sel, SelectionKey.OP_READ);


}
}
else if (e.isReadable()) {
ByteBuffer bb = ByteBuffer.allocate(128);
int nn = ((ByteChannel)(e.channel())).read(bb);
if (nn > 0) {
bb.flip();

byte[] bs = new byte[bb.remaining()];
bb.get(bs, 0, bs.length);
System.out.println("received : " + new String(bs));
System.out.println("server --" + nn);
System.out.println("readable");

bb.clear();

bb.put(new String("server  write-----------").getBytes());
bb.flip();

((ByteChannel)(e.channel())).write(bb);
}
else {
e.channel().close();
}
}
else if (e.isWritable()) {
System.out.println("writable");
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

0 0