socket服务端使用nio的写法

socket服务端使用nio的写法

package NIO;

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;


public class NIOServer {
	// 通道管理器
	private Selector selector;

	/**
	 * 获得一个ServerSocket通道,并对该通道做一些初始化的工作
	 * 
	 * @param port
	 *            绑定的端口号
	 * @throws IOException
	 */
	public void initServer(int port) throws IOException {
		// 获得一个ServerSocket通道
		ServerSocketChannel serverChannel = ServerSocketChannel.open();
		// 设置通道为非阻塞
		serverChannel.configureBlocking(false);
		// 将该通道对应的ServerSocket绑定到port端口
		serverChannel.socket().bind(new InetSocketAddress(port));
		// 获得一个通道管理器
		this.selector = Selector.open();
		// 将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,
		// 当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。
		serverChannel.register(selector, SelectionKey.OP_ACCEPT);
	}

	/**
	 * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
	 * 
	 * @throws IOException
	 */
	public void listen() throws IOException {
		System.out.println("服务端启动成功!");
		// 轮询访问selector
		while (true) {
			// 当注册的事件到达时,方法返回;否则,该方法会一直阻塞
			selector.select();
			// 获得selector中选中的项的迭代器,选中的项为注册的事件
			Iterator<?> ite = this.selector.selectedKeys().iterator();
			while (ite.hasNext()) {
				SelectionKey key = (SelectionKey) ite.next();
				// 删除已选的key,以防重复处理
				ite.remove();

				handler(key);
			}
		}
	}

	/**
	 * 处理请求
	 * 
	 * @param key
	 * @throws IOException
	 */
	public void handler(SelectionKey key) throws IOException {
		
		System.out.println(key.isWritable()); //返回 false,因为没有关注这个事件,如果注册了返回true
		                                      //这个事件表示是否缓冲区是否空闲,通常是空闲的一般不用这个
		// 客户端请求连接事件
		if (key.isAcceptable()) {
			handlerAccept(key);
			// 获得了可读的事件
		} else if (key.isReadable()) {
			handelerRead(key);
		}
	}

	/**
	 * 处理连接请求
	 * 
	 * @param key
	 * @throws IOException
	 */
	public void handlerAccept(SelectionKey key) throws IOException {
		ServerSocketChannel server = (ServerSocketChannel) key.channel();
		// 获得和客户端连接的通道
		SocketChannel channel = server.accept();
		// 设置成非阻塞
		channel.configureBlocking(false);

		// 在这里可以给客户端发送信息哦
		System.out.println("新的客户端连接");
		// 在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。
		channel.register(this.selector, SelectionKey.OP_READ); //通常不使用 SelectionKey.OP_WRITE 
//		channel.register(this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); //这样写就不正常了
	}

	/**
	 * 处理读的事件
	 * 
	 * @param key
	 * @throws IOException
	 */
	public void handelerRead(SelectionKey key) throws IOException {
		// 服务器可读取消息:得到事件发生的Socket通道
		SocketChannel channel = (SocketChannel) key.channel();
		// 创建读取的缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		int read = channel.read(buffer); //如果关闭客户端,这里会抛出异常信息,telnet不抛异常,java客户端抛出异常
										 //循环读取与解码的方式参见 NServer
		if(read > 0){
			byte[] data = buffer.array();
			String msg = new String(data).trim();
			System.out.println("服务端收到信息:" + msg);
			
			//回写数据
			ByteBuffer outBuffer = ByteBuffer.wrap("好的".getBytes());
			channel.write(outBuffer);// 将消息回送给客户端
		}else{
			System.out.println("客户端关闭");
			key.cancel();
		}
	}

	/**
	 * 启动服务端测试
	 * 
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		NIOServer server = new NIOServer();
		server.initServer(8000);
		server.listen();
	}

}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Java NIO 来实现服务端的开发,同时使用普通的 Socket 来实现客户端的开发。下面是一个简单的示例: 服务端代码: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.StandardCharsets; public class NIOServer { public static void main(String[] args) throws IOException { // 创建 ServerSocketChannel 对象 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); // 绑定监听端口 serverSocketChannel.bind(new InetSocketAddress(8888)); // 设置为非阻塞模式 serverSocketChannel.configureBlocking(false); while (true) { // 接受客户端连接 SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel != null) { // 收到客户端连接 System.out.println("接收到客户端连接:" + socketChannel.getRemoteAddress()); // 创建缓冲区 ByteBuffer buffer = ByteBuffer.allocate(1024); // 读取客户端发送的数据 int bytesRead = socketChannel.read(buffer); if (bytesRead > 0) { // 切换缓冲区为读模式 buffer.flip(); // 解码数据 String message = StandardCharsets.UTF_8.decode(buffer).toString(); System.out.println("收到客户端消息:" + message); // 回复客户端 buffer.clear(); buffer.put("Hello, Client!".getBytes(StandardCharsets.UTF_8)); buffer.flip(); socketChannel.write(buffer); } } } } } ``` 客户端代码: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; public class SocketClient { public static void main(String[] args) throws IOException { // 创建 Socket 对象 Socket socket = new Socket(); // 连接服务器 socket.connect(new InetSocketAddress("localhost", 8888)); // 发送消息到服务器 String message = "Hello, Server!"; socket.getOutputStream().write(message.getBytes(StandardCharsets.UTF_8)); // 接收服务器回复的消息 byte[] buffer = new byte[1024]; int bytesRead = socket.getInputStream().read(buffer); if (bytesRead > 0) { String reply = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8); System.out.println("收到服务器消息:" + reply); } // 关闭连接 socket.close(); } } ``` 在上面的示例中,服务端使用 `ServerSocketChannel` 来监听客户端连接,并使用 `SocketChannel` 来读取客户端发送的数据,并回复消息。客户端使用普通的 `Socket` 来连接服务端,并发送消息到服务端,并接收服务端回复的消息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值