Java NIO(6):Server和Client案例

本文详细介绍了使用Java NIO实现Server和Client通信的案例。通过创建Selector、ServerSocketChannel和SocketChannel,展示了如何建立连接、接收与发送数据,揭示了Java NIO在并发处理上的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Server:

package com.tony.app;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
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;

/**
 * 服务器
 * 
 * @author TONY
 *
 */
public class Server {
	// 缓冲区的大小
	private final static int BUFFER_SIZE = 1024;

	// 缓冲区
	private ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);

	// Server监听的端口号
    // private final static int PORT = 8888;

	// 选择器
	private Selector selector = null;

	// 初始化工作
	public void init(int port) throws IOException {
		System.out.println("============ Listening On Port : " + port + "============");
		// 打开服务器套接字通道
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		// 设置为非阻塞状态
		serverSocketChannel.configureBlocking(false);
		// 获取通道相关联的套接字
		ServerSocket serverSocket = serverSocketChannel.socket();
		// 绑定端口号
		serverSocket.bind(new InetSocketAddress(port));
		// 打开一个选择器
		selector = Selector.open();
		// 服务器套接字注册到Selector中 并指定Selector监控连接事件
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
	}

	public void listen() throws IOException {
		while (true) {
			// 开启选择
			int readyChannels = selector.select(); // 没有通道就绪 一直
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值