您的位置:首页 > 理论基础 > 计算机网络

网络编程(3)--使用NIO实现Socket通信

2014-10-10 19:51 295 查看
public class NServer

{

private Selector selector = null;

private Charset charset = Charset.forName("UTF-8");

public void init() throws IOException

{

selector = Selector.open();

ServerSocketChannel server = ServerSocketChannel.open();

InetSocketAddress isa = new InetSocketAddress("127.0.0.1",30000);

server.socket().bind(isa);

server.configureBlocking(false);

server.register(selector,SelectionKey.OP_ACCEPT);

while(selector.select() > 0)

{

for(SelectionKey sk : selector.selectedKeys())

{

selector.selectedKeys().remove(sk);

if(sk.isAcceptable())

{

SocketChannel sc = server.accept();

sc.configureBlocking(false);

sc.register(selector,SelectionKey.OP_READ);

sk.interestOps(SelectionKey.OP_ACCEPT);

}

if(sk.isReadable())

{

SocketChannel sc = (SocketChannel)sk.channel();

ByteBuffer buff = ByteBuffer.allocate(1024);

String content = "";

try

{

while(sc.read(buff) > 0)

{

buff.flip();

content += charset.decode(buff);

}

System.out.println("=====" + content);

sk.intersetOps(SelectionKey.OP_READ);

}

catch (IOException ex)

{

sk.canel();

if(sk.channel() != null)

{

sk.channel().close();

}

}

if(content.length() > 0)

{

for(SelectionKey key : selector.keys())

{

Channel targetChannel = key.channel();

if(targetChannel instanceof SocketChannel)

{

SocketChannel dest = (SocketChannel)targetChannel;

dest.write(charset.encode(content));

}

}

}

}

}

}

}

public static void main(String[] args) throws IOException

{

new NServer().init();

}

}

public class NClient

{

private Selector selector = null;

private Charset charset = Charset.forName("UTF-8");

private SocketChannel sc = null;

public void init() throws IOException

{

selector = Selector.open();

InetSocketAddress isa = new InetSocketAddress("127.0.0.1",30000);

sc = SocketChannel.open(isa);

sc.configureBlocking(false);

sc.register(selector,SelectionKey.OP_READ);

new ClientThread().start();

Scanner scan = new Scanner(System.in);

while(scan.hasNextLine())

{

String line = scan.nextLine();

sc.write(charset.encode(line));

}

}

private class ClientThread extends Thread

{

public void run()

{

try

{

while(selector.select() > 0 )

{

for(SelectionKey sk : selector.selectedKeys())

{

selector.selectedKeys().remove(sk);

if(sk.isReadable())

{

SocketChannel sc = (SocketChannel)sk.channel();

ByteBuffer buff = ByteBuffer.allocate(1024);

String content = "";

while(sc.read(buff) > 0)

{

sc.read(buff);

buff.flip();

content +=charset.decode(buff);

}

System.out.println("聊天信息:"+content);

sk.interestOps(SelectionKey.OP_READ);

}

}

}

catch(IOException ex)

{

ex.printStackTrace();

}

}

}

public static void main(String[] args) throws IOException

{

new NClient().init();

}

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