当前位置:首页 > 开发 > 编程语言 > 网络编程 > 正文

nio socket

发表于: 2013-01-16   作者:blackproof   来源:转载   浏览次数:
摘要: 先看一下以前写的socket服务器:   --old socket server: serversocket对象server 指定port 调用accept方法阻塞 用输入输出流socket.getInputStream() , socket.getOutputStream() 向客户端接受发送信息   client: socket对象client 指定ip

先看一下以前写的socket服务器:

 

--old socket

server:

serversocket对象server 指定port

调用accept方法阻塞

用输入输出流socket.getInputStream() , socket.getOutputStream()

向客户端接受发送信息

 

client:

socket对象client 指定ip和port

用输入输出流socket.getInputStream() , socket.getOutputStream()

向客户端接受发送信息

 

//server	
public void initSocketServer() throws IOException{
		ServerSocket server = null;
		server = new ServerSocket(10100);
		Socket socket = server.accept();
		String line;
		BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		PrintWriter os = new PrintWriter(socket.getOutputStream());
		line = "server start and send msg1";
		os.println(line);
		os.flush();
		System.out.println("cient:"+is.readLine());
		is.close();
		os.close();
	}



//client
	public void clientSocket() throws UnknownHostException, IOException{
		Socket socket = new Socket("localhost",10100);
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
		PrintWriter pw = new PrintWriter(socket.getOutputStream());
		String line = reader.readLine();
		System.out.println("server: "+line);
		pw.write("dirk come back");
		pw.flush();
		reader.close();
		pw.close();
	}

 

 

接下来是nio socket:

 

 

 

--new socket

server:

serverSocketChannel对象 用open实例化

管道调用configureBlocking设置是否阻塞

管道绑定端口serverChannel.socket().bind(new InetSocketAddress(port));

开启管道管理器Selector.open();

注册server accept client事件

 

循环遍历

调用selector.select()方法阻塞,直到有注册的事件 如客户端channel.connect(new InetSocketAddress(host, port));

遍历事件

当是accept时,注册读事件

当是

 

client:

SocketChannel对象 用open实例化

管道调用configureBlocking设置是否阻塞

管道绑定host和port  channel.connect(new InetSocketAddress(host, port)); //发起accept事件

开启管道管理器Selector.open();

注册client connect server事件

 

循环遍历

selector.select();

遍历事件

当有connet时,注册read事件,删除connet事件

 

 

server:

 

public class NewSocketServer {
	private Selector selector;
	
	public void initServer(int port) throws IOException{
		ServerSocketChannel serverChannel = ServerSocketChannel.open();
		serverChannel.configureBlocking(false);
		serverChannel.socket().bind(new InetSocketAddress(port));
		this.selector = Selector.open();
		serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
	}
	
	public void listen() throws IOException{
		System.out.println("server start");
		while(true){
			selector.select();
			Iterator ite = this.selector.selectedKeys().iterator();
			while(ite.hasNext()){
				SelectionKey key = (SelectionKey) ite.next();
				ite.remove();
				if(key.isAcceptable()){
					ServerSocketChannel server = (ServerSocketChannel)key.channel();
					SocketChannel channel = server.accept();
					channel.configureBlocking(false);
					channel.write(ByteBuffer.wrap(new String("server: server start and send msg").getBytes()));
					channel.register(this.selector, SelectionKey.OP_READ);
				}else if(key.isReadable())
					read(key);
			}
		}
	}
	
	public void read(SelectionKey key) throws IOException{
		if(key.channel() instanceof ServerSocketChannel)
			System.out.println("server: serverchannel read");
		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buffer = ByteBuffer.allocate(100);
		channel.read(buffer);
		buffer.flip();
		byte[] data = new byte[buffer.limit()];
		buffer.get(data);
		System.out.println("服务器收到信息:"+new String(data));
		ByteBuffer outbuffer = ByteBuffer.wrap(new String("服务器返回信息").getBytes());
		channel.write(outbuffer);
	}
	
	public static void main(String[] args) throws IOException{
		NewSocketServer server = new NewSocketServer();
		server.initServer(10110);
		server.listen();
	}

}

 

client:

 

public class NewSocketClient {
	
	private Selector selector;
	
	public void initClient(String host,int port) throws IOException{
		SocketChannel channel = SocketChannel.open();
		channel.configureBlocking(false);
		this.selector = Selector.open();
		channel.connect(new InetSocketAddress(host, port));
		channel.register(this.selector, SelectionKey.OP_CONNECT);
	}
	
	public void listen() throws IOException{
		while (true) {
			selector.select();
			for (Iterator iterator = this.selector.selectedKeys().iterator(); iterator.hasNext();) {
				SelectionKey key = (SelectionKey) iterator.next();
				iterator.remove();
				if(key.isConnectable()){
					SocketChannel channel = (SocketChannel) key.channel();
					if(channel.isConnectionPending())
						channel.finishConnect();
					channel.configureBlocking(false);
					channel.write(ByteBuffer.wrap(new String("dirk coming back").getBytes()));
					channel.register(this.selector, SelectionKey.OP_READ);
				}else if(key.isReadable())
					read(key);
			}
		}
	}
	
	
	public void read(SelectionKey key) throws IOException{
		if(key.channel() instanceof ServerSocketChannel)
			System.out.println("server: serverchannel read");
		SocketChannel channel  = (SocketChannel) key.channel();
		ByteBuffer bb = ByteBuffer.allocate(100);
		channel.read(bb);
		bb.flip();
		byte[] b = new byte[bb.limit()];
		bb.get(b);
		System.out.println(new String(b));
		channel.write(ByteBuffer.wrap(new String("客户端返回信息").getBytes()));
		
	}
	
	public static void main(String[] args) throws IOException {
		NewSocketClient client = new NewSocketClient();
		client.initClient("localhost", 10110);
		client.listen();
	}

}

 

 

 转 http://weixiaolu.iteye.com/blog/1479656

 

 

nio socket

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
TCP/IP协议 要编写计算机网络编程,首先要了解这些程序相互通信所使用的协议。 IP层接收由更低层(
Java NIO (Nonblocking IO)解决了常规IO的瓶颈: a. 服务端的监听操作会阻塞而无法处理其它事务。多
Java NIO (Nonblocking IO)解决了常规IO的瓶颈: a. 服务端的监听操作会阻塞而无法处理其它事务。多
Java NIO (Nonblocking IO)解决了常规IO的瓶颈: a. 服务端的监听操作会阻塞而无法处理其它事务。多
之前的 I/O 编程 在 JDK 1.4 之前,自由地使用线程是处理阻塞问题最典型的办法。但这个解决办法会产
Java NIO (Nonblocking IO)解决了常规IO的瓶颈: a. 服务端的监听操作会阻塞而无法处理其它事务。多
Java NIO (Nonblocking IO)解决了常规IO的瓶颈: a. 服务端的监听操作会阻塞而无法处理其它事务。多
直接上代码,后续文章会有io,nio比较.. ServerMain.java package test.server; import java.io.IOExc
传统的Java 的IO,利用Socket建立服务器,接收客户端连接,一般都是为每一个连接建立一个线程,如果
在基础网络协议上,java 支持TCP/IP 和UDP/IP。在网络操作上java支持BIO和NIO(新I/O可以查看http://
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号