NIO实现的客户端与服务端之间的通信

1 服务端启动类

public class TimeServer {
public static void main(String[] args) {
int port = 8080;
//这个类负责轮询多路复用器 selector
MultiplexerTimerServer mts = new MultiplexerTimerServer(port);
//单独开启一个线程来执行mts服务
new Thread(mts,“NIO-MultiplexerTimerServer-001”).start();
}
}
2:服务端请求处理类

public class MultiplexerTimerServer implements Runnable{

private Selector selector;

private ServerSocketChannel serverSocketChannel;

private volatile boolean stop;

public MultiplexerTimerServer(int port) {
	try {
		//创建多路复用器 selector
		selector = Selector.open();
		serverSocketChannel = ServerSocketChannel.open();
		//将serverSocketChannel设置为非阻塞模式
		serverSocketChannel.configureBlocking(false);
		//serverSocketChannel的socket绑定服务端口 并设置TCP参数
		serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);
		//将serverSocketChannel 注册到selector上,并让selector监听SelectionKey 的OP_ACCEPT操作位
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		System.out.println("============MultiplexerTimerServer is start in port "+port);
	} catch (IOException e) {
		e.printStackTrace();
		System.exit(1);
	}
}

/**
 * 关闭MultiplexerTimerServer服务
 */
public void stop() {
	stop = true;
}

@Override
public void run() {
	while (!stop) {
		try { 
			//休眠1秒  无论是否有读写事件发生 selector每隔1秒被唤醒
			selector.select(1000);
			//获取注册在selector上的所有的就绪状态的serverSocketChannel中发生的事件
			Set<SelectionKey> selectedKeys = selector.selectedKeys();
			Iterator<SelectionKey> iterators = selectedKeys.iterator();
			SelectionKey key = null;
			while (iterators.hasNext()) {
				key = iterators.next();
				iterators.remove();
				try {
					handleInput(key);
				} catch (Exception e) {
					if (key != null) {
						key.cancel();
						if (key.channel() != null) {
							key.channel().close();
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	if (selector != null) { //服务停止 关闭selector
		try {
			selector.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

/**
 * 处理客户端新接入的请求
 * @param key 请求信息
 * @throws IOException
 */
private void handleInput(SelectionKey key) throws IOException{
	if (key.isValid()) {
		//处理新接入的请求消息
		if (key.isAcceptable()) {
			ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
			SocketChannel sc = ssc.accept();
			sc.configureBlocking(false);
			sc.register(selector,SelectionKey.OP_READ);
		}

		if (key.isReadable()) {
			//获取SocketChannel实例后,相当于完成了TCP三次握手,TCP物理链路正式建立
			SocketChannel sc = (SocketChannel) key.channel();
			ByteBuffer readBuffer = ByteBuffer.allocate(1024);
			//读取客户端传过来的请求参数
			int readBytes = sc.read(readBuffer);

			if (readBytes > 0) {//获取到了请求数据,对字节进行编解码
				readBuffer.flip();
				byte[] bytes = new byte[readBuffer.remaining()];
				readBuffer.get(bytes);

				String requestMessage = new String(bytes, Charset.forName("UTF-8"));
				System.out.println("============MultiplexerTimerServer receive message:"+requestMessage);
				doWrite(sc,"responseMessage");
			} else if (readBytes < 0) {//没有获取到请求数据,需要关闭SocketChannel(C/S 连接链路)
				key.cancel();
				sc.close();
			}
		}
	}
}

/**
 * 将请求的响应 异步返回给客户端
 * @param sc (C/S 连接链路)
 * @param response 响应数据
 * @throws IOException
 */
private void doWrite(SocketChannel sc, String response) throws IOException {
	if (response != null && !response.isEmpty()) {
		byte[] bytes = response.getBytes();
		ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
		buffer.put(bytes);
		buffer.flip();
		sc.write(buffer);
	}
}

}
3:客户端启动类

public class TimeClient {
public static void main(String[] args) {
//服务器端的端口
int port = 8080;
//这个类负责轮询多路复用器 selector
TimeClientHandle tch = new TimeClientHandle(“127.0.0.1”,port);
//单独开启一个线程来执行tch服务
new Thread(tch,“NIO-TimeClient-001”).start();
}
}
4:客户端实现类

public class TimeClientHandle implements Runnable {

private String ip;

private int port;

private Selector selector;

private SocketChannel socketChannel;

private volatile boolean stop;

public TimeClientHandle (String ip,int port) {
	this.ip = ip == null ? "127.0.0.1" : ip;
	this.port = port;

	try {
		selector = Selector.open();
		socketChannel = SocketChannel.open();
		socketChannel.configureBlocking(false);
	} catch (IOException e) {
		e.printStackTrace();
		System.exit(1);
	}
}

@Override
public void run() {

	try {
		doConnect(); //请求建立连接
	} catch (IOException e) {
		e.printStackTrace();
	}

	while (!stop) {

		try {
			//休眠1秒  无论是否有读写事件发生 selector每隔1秒被唤醒
			selector.select(1000);
			//获取注册在selector上的所有的就绪状态的serverSocketChannel中发生的事件
			Set<SelectionKey> set = selector.selectedKeys();
			Iterator<SelectionKey> it = set.iterator();
			SelectionKey key = null;
			while (it.hasNext()) {
				key = it.next();
				it.remove();

				try {
					handleInput(key);
				} catch (Exception e) {
					if (key != null) {
						key.cancel();
						if (key.channel() != null) {
							key.channel().close();
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	if (selector != null) {
		try {
			selector.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

private void handleInput(SelectionKey key) throws IOException {
	if (key.isValid()) {
		SocketChannel sc = (SocketChannel) key.channel();
		if (key.isConnectable()) { //处于连接状态
			if (sc.finishConnect()) {//客户端连接成功
				sc.register(selector, SelectionKey.OP_READ);
				doWrite(sc);
			} else { //连接失败
				System.exit(1);
			}
		}

		if (key.isReadable()) {//如果客户端接收到了服务器端发送的应答消息 则SocketChannel是可读的
			ByteBuffer bf = ByteBuffer.allocate(1024);
			int bytes = sc.read(bf);
			if (bytes > 0) {
				bf.flip();
				byte[] byteArray = new byte[bf.remaining()];
				bf.get(byteArray);
				String resopnseMessage = new String(byteArray, "UTF-8");
				System.out.println("=======The response message is:"+resopnseMessage);
				this.stop = true;
			} else if (bytes < 0) {
				key.cancel();
				sc.close();
			}
		}
	}
}

private void doConnect() throws IOException {
	//如果直连接连接成功,则注册到多路复用器上,并注册SelectionKey.OP_READ操作
	if (socketChannel.connect(new InetSocketAddress(ip, port))) {
		socketChannel.register(selector, SelectionKey.OP_READ);
		//发送请求消息 读应答
		doWrite(socketChannel);
	} else {//如果直连接连接未成功,则注册到多路复用器上,并注册SelectionKey.OP_CONNECT操作
		socketChannel.register(selector, SelectionKey.OP_CONNECT);
	} 
}

private void doWrite(SocketChannel sc) throws IOException {

	byte[] requestBytes = "request message from client".getBytes();
	ByteBuffer bf = ByteBuffer.allocate(requestBytes.length);
	bf.put(requestBytes);
	bf.flip();
	sc.write(bf);

	if (!bf.hasRemaining()) {//如果缓冲区里面的所有内容全部发送完毕
		System.out.println("=======client send requst message to server successed!");
	}
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 NIO(Non-blocking I/O)实现 Java 的客户端服务端可以提高网络通信的效率。下面是一个简单的示例,演示了如何使用 NIO 实现一个简单的客户端服务端。 首先是服务端代码: ```java 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.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class NioServer { private static int BUF_SIZE = 1024; private static int PORT = 8080; private static int TIMEOUT = 3000; public static void main(String[] args) { selector(); } public static void handleAccept(SelectionKey key) throws IOException { ServerSocketChannel ssChannel = (ServerSocketChannel) key.channel(); SocketChannel sc = ssChannel.accept(); sc.configureBlocking(false); sc.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocateDirect(BUF_SIZE)); } public static void handleRead(SelectionKey key) throws IOException { SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); int bytesRead = sc.read(buf); while (bytesRead > 0) { buf.flip(); while (buf.hasRemaining()) { System.out.print((char) buf.get()); } System.out.println(); buf.clear(); bytesRead = sc.read(buf); } if (bytesRead == -1) { sc.close(); } } public static void handleWrite(SelectionKey key) throws IOException { ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); SocketChannel sc = (SocketChannel) key.channel(); while (buf.hasRemaining()) { sc.write(buf); } buf.compact(); } public static void selector() { Selector selector = null; ServerSocketChannel ssc = null; try { selector = Selector.open(); ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(PORT)); ssc.configureBlocking(false); ssc.register(selector, SelectionKey.OP_ACCEPT); while (true) { if (selector.select(TIMEOUT) == 0) { System.out.println("=="); continue; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isAcceptable()) { handleAccept(key); } if (key.isReadable()) { handleRead(key); } if (key.isWritable() && key.isValid()) { handleWrite(key); } if (key.isConnectable()) { System.out.println("isConnectable = true"); } iterator.remove(); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (selector != null) { selector.close(); } if (ssc != null) { ssc.close(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 然后是客户端代码: ```java 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.util.Iterator; import java.util.Scanner; import java.util.Set; public class NioClient { private static int BUF_SIZE = 1024; private static int PORT = 8080; private static int TIMEOUT = 3000; public static void main(String[] args) throws IOException { SocketChannel clientChannel = SocketChannel.open(); clientChannel.configureBlocking(false); Selector selector = Selector.open(); clientChannel.register(selector, SelectionKey.OP_CONNECT); clientChannel.connect(new InetSocketAddress(PORT)); while (true) { if (selector.select(TIMEOUT) == 0) { System.out.println("=="); continue; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isConnectable()) { SocketChannel channel = (SocketChannel) key.channel(); if (channel.isConnectionPending()) { channel.finishConnect(); } channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); Scanner scanner = new Scanner(System.in); String message = scanner.nextLine(); channel.write(ByteBuffer.wrap(message.getBytes())); } else if (key.isReadable()) { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(BUF_SIZE); int bytesRead = channel.read(buffer); while (bytesRead > 0) { buffer.flip(); while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } System.out.println(); buffer.clear(); bytesRead = channel.read(buffer); } } iterator.remove(); } } } } ``` 这里的服务端监听端口为 8080,客户端连接的端口也为 8080。客户端首先向服务端发送一条消息,然后等待服务端的响应。当服务端接收到客户端消息后,就会输出到控制台,并将消息原封不动地返回给客户端客户端接收到服务端的响应后,也会将其输出到控制台。 注意,这个示例只是一个简单的演示,实际开发中需要考虑更多的因素,例如线程安全、异常处理等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值