TCP/NIO示例代码

package rpc;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

public class NioClient {
	private static Selector selector = null;
	private static Charset charset = Charset.forName("UTF-8");
	private ClientThread thread = new ClientThread();

	public static void main(String[] args) throws IOException {
		selector = Selector.open();
		InetSocketAddress address = new InetSocketAddress("127.0.0.1",30000);
		SocketChannel channel = SocketChannel.open(address);
		channel.configureBlocking(false);
		channel.register(selector, SelectionKey.OP_READ);
		new NioClient().thread.start();
		Scanner scan = new Scanner(System.in);
		while(scan.hasNextLine()){
			String line = scan.nextLine();
			channel.write(charset.encode(line));
		}
	}
	private class ClientThread extends Thread{
		public void run(){
			try {
				while(selector.select()>0){
					for(SelectionKey key : selector.selectedKeys()){
						selector.selectedKeys().remove(key);
						if(key.isReadable()){
							SocketChannel sc = (SocketChannel) key.channel();
							System.out.println(" the remote port to which this socket is connected"+sc.socket().getPort());
							System.out.println(" the Local port to which this socket is connected"+sc.socket().getLocalPort());
							ByteBuffer buf = ByteBuffer.allocate(1024);		
							String content ="";
							while(sc.read(buf)>0){
								sc.read(buf);
								buf.flip();
								content += charset.decode(buf);
							}
							System.out.println("ClientThread:"+content);
							key.interestOps(SelectionKey.OP_READ);
									
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

package rpc;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class NioServer {

	public static void main(String[] args) throws IOException {
		//A selectable channel for stream-oriented listening sockets.
		ServerSocketChannel server = ServerSocketChannel.open();
		//implements an IP Socket Address (IP address + port number) 
		InetSocketAddress address = new InetSocketAddress("127.0.0.1", 30000);
		//Binds the ServerSocket to a specific address
		server.socket().bind(address);
		//Adjusts this channel's blocking mode
		server.configureBlocking(false);
		//Opens a selector
		Selector selector = Selector.open();
		//Registers this channel with the given selector, returning a selection key
		server.register(selector, SelectionKey.OP_ACCEPT);
		Charset charset = Charset.forName("UTF-8");
		while(selector.select()>0){
			for(SelectionKey sk : selector.selectedKeys()){
				//Removes the specified element from this set if it is present (optional operation). 
				selector.selectedKeys().remove(sk);
				if(sk.isAcceptable()){
					SocketChannel socketChannel = server.accept();
					socketChannel.configureBlocking(false);
					socketChannel.register(selector, SelectionKey.OP_READ);
					System.out.println(" the remote port to which this socket is connected"+socketChannel.socket().getPort());
					System.out.println(" the Local port to which this socket is connected"+socketChannel.socket().getLocalPort());
					sk.interestOps(SelectionKey.OP_ACCEPT);
				}
				if(sk.isReadable()){
					SocketChannel socketChannel = (SocketChannel) sk.channel();
					System.out.println(" the remote port to which this socket is connected"+socketChannel.socket().getPort());
					System.out.println(" the Local port to which this socket is connected"+socketChannel.socket().getLocalPort());
					ByteBuffer buff = ByteBuffer.allocate(1024);
					String content ="";
					try {
						while(socketChannel.read(buff)>0){
							buff.flip();				
							content += charset.decode(buff);
						}
						System.out.println("server receive:"+content);
						sk.interestOps(SelectionKey.OP_READ);
					} catch (Exception e) {
						sk.cancel();
						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 channel = (SocketChannel) targetChannel;
								channel.write(charset.encode(content+"server写入"));
							}
						}
					}
				}
			}
		}

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值