您的位置:首页 > 编程语言 > Java开发

java nio

2016-05-14 20:15 357 查看
server:

package com.zyw.javaio.test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Server3 {
public static void main(String[] args) {
try {
//return new Selector
Selector selector=Selector.open();
//return ssc
ServerSocketChannel ssc=ServerSocketChannel.open();
ssc.configureBlocking(false);
ServerSocket ss=ssc.socket();
ss.bind(new InetSocketAddress(8888));
ssc.register(selector, SelectionKey.OP_ACCEPT);
ServerSocketChannel ssc1=ServerSocketChannel.open();
ssc1.configureBlocking(false);
ServerSocket ss1=ssc1.socket();
ss1.bind(new InetSocketAddress(9999));
// SelectionKey mark this SSC.
ssc1.register(selector, SelectionKey.OP_ACCEPT);
while (true){
int caseNum=selector.select();
if (caseNum==0){continue;}
//we case thing is hanppening
Set<SelectionKey> keys=selector.selectedKeys();
Iterator it=keys.iterator();
while (it.hasNext()){
SelectionKey sk=(SelectionKey) it.next();

if (sk.isAcceptable()){
// dont worry  about accept  blocking.
ServerSocketChannel sl=(ServerSocketChannel) sk.channel();
SocketChannel sc1=sl.accept();
sc1.configureBlocking(false);
//now newconnect can read.
SelectionKey newKey = sc1.register( selector, SelectionKey.OP_READ );
System.out.println(sk+"can read");
it.remove();
}else if(sk.isReadable()){
SocketChannel sl=(SocketChannel) sk.channel();
ByteBuffer buffer=ByteBuffer.allocate(1024);
try{
sl.read(buffer);
}
catch(Exception ex){
sl.close();
}
System.out.println(new String(buffer.array()));
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


client:

package com.zyw.javaio.test;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

public static void main(String[] args) {
try {
Socket sc=new Socket("127.0.0.1",9999);
OutputStream out=sc.getOutputStream();
out.write("hello server!!! I want to connect.".getBytes());
out.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch blockG
e.printStackTrace();
}
}

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: