厚德博学 敬业乐群
@sky
全部博文(252)
2015年(2)
2014年(1)
2013年(1)
2012年(16)
2011年(42)
2010年(67)
2009年(87)
2008年(36)
25742040
shijiulo
niuxlinu
ebayboy
hayand66
大鬼不动
acer1025
醉鬼的故
小雅贝贝
XINGCHEN
wzy_yzw
十的9次
zds05
bjywxc
zlhc1
smile124
cynthia
格伯纳
分类:
2009-06-26 11:33:04
import java.io.*; import java.net.*; import java.nio.*; import java.nio.channels.*; public class client { public static void main(String args[]) throws Exception { SocketChannel channel = SocketChannel.open(); channel.socket().connect(new InetSocketAddress("127.0.0.1", 8888)); ByteBuffer buf = ByteBuffer.allocate(20); buf.clear(); buf.put((byte)'a'); buf.put((byte)'b'); buf.put((byte)'c'); buf.flip(); int written = channel.write(buf); buf.clear(); int len = channel.read(buf); buf.flip(); for (int i = 0; i < len; i++) System.out.print((char)buf.get(i)); System.out.println(""); channel.close(); } }
import java.io.*; import java.nio.*; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.net.*; import java.util.Iterator; public class ServerNio { static Selector selector; public static void handle(SelectionKey key) throws Exception { if (key.isAcceptable()) { ServerSocketChannel channel = (ServerSocketChannel) key.channel(); SocketChannel socket = channel.accept(); socket.configureBlocking(false); socket.register(selector, SelectionKey.OP_READ); } if (key.isReadable()) { SocketChannel socket = (SocketChannel) key.channel(); ByteBuffer buf = ByteBuffer.allocate(1024); int len; try { buf.clear(); if ((len = socket.read(buf)) <= 0) { socket.close(); key.cancel(); return; } buf.flip(); socket.write(buf); } catch(Exception e) { e.printStackTrace(); } } } public static void main(String[] args) throws Exception { selector = Selector.open(); ServerSocketChannel server = ServerSocketChannel.open(); server.configureBlocking(false); server.socket().bind(new InetSocketAddress(8888)); server.register(selector, SelectionKey.OP_ACCEPT); while (true) { selector.select(); Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); if (key.isValid()) { handle(key); } keyIterator.remove(); } } } }
上一篇:echo服务器(任意数据)
下一篇:java 连接mysql数据库方法
登录 注册