3.Netty之一个基于NIO的服务端

本文介绍了一个基于 Java NIO 的服务端实现案例。通过创建 Selector 和 ServerSocketChannel 来处理客户端连接请求,并实现了非阻塞模式下的读写操作。

看了一下《Java NIO》这本书,然后尝试着写了一个服务端demo

package com.bj58.pn.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 NonIOServer implements Runnable {
	Selector selector;

	public NonIOServer(int port) throws IOException {
		// 0.开启selector监听器
		selector = Selector.open();
		// 1.开启通道
		ServerSocketChannel ssc = ServerSocketChannel.open();
		// 2.通道监听端口
		ssc.bind(new InetSocketAddress(port));
		// 3.设置通道属性(非阻塞)
		ssc.configureBlocking(Boolean.FALSE);
		// 4.注册到selector选择器
		ssc.register(selector, SelectionKey.OP_ACCEPT);
	}

	@Override
	public void run() {
		while (true) {
			try {
				// 1.开始监听
				selector.select();
				// 2.获取多路复用器选择的结果集
				Iterator<SelectionKey> it = selector.selectedKeys().iterator();
				while (it.hasNext()) {
					SelectionKey key = it.next();
					it.remove();
					if (key.isValid() && key.isAcceptable()) {
						doAccept(key);
					}
					if (key.isValid() && key.isReadable()) {
						doRead(key);
					}
					if (key.isValid() && key.isWritable()) {
						doWrite(key);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void doAccept(SelectionKey key) {
		try {
			SocketChannel sc = ((ServerSocketChannel) key.channel()).accept();
			sc.configureBlocking(Boolean.FALSE);
			sc.register(selector, SelectionKey.OP_READ);
		} catch (IOException e) {
			System.out.println("accept 异常");
			e.printStackTrace();
		}

	}

	private void doRead(SelectionKey key) {
		SocketChannel sc = (SocketChannel) key.channel();
		ByteBuffer reqBuffer = ByteBuffer.allocate(2048);

		try {
			int i = sc.read(reqBuffer);
			if (i >= 0) {
				reqBuffer.flip();
				byte[] bytes = new byte[reqBuffer.remaining()];
				reqBuffer.get(bytes);
				System.out.println(new String(bytes));
				key.attach("res");
				key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
			} else {
				sc.close();
			}
		} catch (IOException e) {
			System.out.println("read 异常");
			try {
				sc.close();
				sc.socket().close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	private void doWrite(SelectionKey key) {
		SocketChannel sc = (SocketChannel) key.channel();
		String handle = (String) key.attachment();// 取出read方法传递的信息。
		ByteBuffer retBuffer = ByteBuffer.wrap(handle.getBytes());

		try {
			sc.write(retBuffer);
			sc.close();
		} catch (IOException e) {
			System.out.println("write 异常");
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws IOException {
		System.out.println("正在启动服务...");
		new Thread(new NonIOServer(8000)).start();
	}

}

 

11:24:25.865 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework 11:24:25.868 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - -Dio.netty.noUnsafe: false 11:24:25.869 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - Java version: 8 11:24:25.869 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available 11:24:25.869 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.storeFence: available 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - java.nio.Buffer.address: available 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - direct buffer constructor: available 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: available, true 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable prior to Java9 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent0 - java.nio.DirectByteBuffer.<init>(long, int): available 11:24:25.870 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - sun.misc.Unsafe: available 11:24:25.871 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - -Dio.netty.tmpdir: C:\Users\admin\AppData\Local\Temp (java.io.tmpdir) 11:24:25.871 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - -Dio.netty.bitMode: 64 (sun.arch.data.model) 11:24:25.871 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - Platform: Windows 11:24:25.871 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - -Dio.netty.maxDirectMemory: 7570718720 bytes 11:24:25.871 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - -Dio.netty.uninitializedArrayAllocationThreshold: -1 11:24:25.872 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.CleanerJava6 - java.nio.ByteBuffer.cleaner(): available 11:24:25.872 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - -Dio.netty.noPreferDirect: false 11:24:26.010 [main] DEBUG io.grpc.netty.shaded.io.netty.channel.MultithreadEventLoopGroup - -Dio.netty.eventLoopThreads: 48 11:24:26.018 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.InternalThreadLocalMap - -Dio.netty.threadLocalMap.stringBuilder.initialSize: 1024 11:24:26.018 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.InternalThreadLocalMap - -Dio.netty.threadLocalMap.stringBuilder.maxSize: 4096 11:24:26.021 [main] DEBUG io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop - -Dio.netty.noKeySetOptimization: false 11:24:26.021 [main] DEBUG io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop - -Dio.netty.selectorAutoRebuildThreshold: 512 11:24:26.024 [main] DEBUG io.grpc.netty.shaded.io.netty.util.internal.PlatformDependent - org.jctools-core.MpscChunkedArrayQueue: available客户端运行结果如下,请分析并提出解决方案
08-26
C:\Windows\system32\cmd.e:x + zation(InitDestroyAnnotationBeanPostProcessor.java:136) ...26 common frames omittedCaused by: java.net.BindException: Address already in use: bindsun.nio.ch.Net.bind(Native Method)atatsun.nio.ch.Net.bind(Net.java:433)at sun.nio.ch.Net.bind(Net.java:425)sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)atat io .grpc.netty.shaded. io.netty.channel.socket.nio.NioServerSocketchannel.doBind(NioServerSocketchannel.java:13at io . grpc.netty.shaded.io.netty.channel.Abstractchannel$AbstractUnsafe.bind(Abstractchannel.java:551)at io .grpc.netty.shaded. io.netty.channel.DefaultchannelPipeline$HeadContext.bind(DefaultchannelPipeline.java:134at io .grpc.netty.shaded.io.netty.channel.AbstractchannelHandlerContext.invokeBind(AbstractChannelHandlerContextat io.grpc.netty.shaded.io.netty.channel.AbstractchannelHandlerContext.bind(AbstractchannelHandlerContext.java:4at io.grpc .netty.shaded.io.netty.channel.Defaultchannelpipeline.bind(DefaultchannelPipeline.java:985)atio.grpc.nettyshaded.io.netty.channel.AbstractChannel.bind(Abstractchannel.java:247)atio.grpc.netty.shaded.io.netty..bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:344)at io.grpc.netty.shaded, io.netty.util,concurrent.AbstractEventExecutor,safeExecute(AbstractEventExecutor.java:16 2) 0 java:503) 88) at io .grpc.netty,shaded. io.netty.util.concurrent .singleThreadEventExecutor.runAllTasks(SingleThreadEventExecutorio.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:518)io.grpc.netty..shaded.at io.grpc.netty.shaded. io.netty.util.concurrent ,singleThreadEventExecutor$6.run(SingleThreadEventExecutor .javaat io.grpc.netty.shaded.io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)at io.grpc.netty.shaded. io.netty.util.concurrent .FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)at java.lang.Thread.run(Thread.iava:748) at java:510) 1044)
03-11
io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2Exception: Unexpected HTTP/1.x request: POST /user/login at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2Exception.connectionError(Http2Exception.java:109) ~[grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.readClientPrefaceString(Http2ConnectionHandler.java:317) ~[grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.decode(Http2ConnectionHandler.java:247) ~[grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:453) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:529) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:468) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:290) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:440) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:788) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) [grpc-netty-shaded-1.54.0.jar:1.54.0] at io.grpc.netty.shaded.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) [grpc-netty-shaded-1.54.0.jar:1.54.0] at java.lang.Thread.run(Thread.java:748) [na:1.8.0_221]
最新发布
08-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值