简单SocketChannel 服务端和客户端连接

本文介绍如何利用SocketChannel在Java中建立服务端和客户端的连接。服务端通过SocketChannel监听客户端的连接请求,客户端则创建SocketChannel与服务端建立连接,实现双向数据传输。
摘要由CSDN通过智能技术生成

服务端代码:

public static void main(String[] args) throws Exception 
	{
		// 创建选择器  
		Selector selector = Selector.open();
		// 打开监听信道  
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		// 与本地端口绑定  
		serverSocketChannel.socket().bind(new InetSocketAddress(9999));
		// 设置为非阻塞模式 
		serverSocketChannel.configureBlocking(false); 
		// 将选择器绑定到监听信道,只有非阻塞信道才可以注册选择器.并在注册过程中指出该信道可以进行Accept操作  
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		
		while (true) 
		{
			// 等待某信道就绪
			int selectInt = selector.select();
			if (selectInt == 0)
				continue;
			// 取得迭代器.selectedKeys()中包含了每个准备好某一I/O操作的信道的SelectionKey
			Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
			while (iterator.hasNext())
			{
				SelectionKey selectionKey = iterator.next();
				// 有客户端连接请求时 
				if (selectionKey.isAcceptable())
					handleAccept(selectionKey);
				// 从客户端读取
Netty是一个基于Java的网络编程框架,可以用于构建高性能、可扩展的网络应用程序。Netty的短连接服务端客户端的实现如下: 服务端: ```java public class ShortConnectionServer { public static void main(String[] args) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new ServerHandler()); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = bootstrap.bind(8080).sync(); future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } public class ServerHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) { // 处理客户端发送的请求 System.out.println("Received message from client: " + msg); // 回复客户端 ctx.writeAndFlush("Hello from server!"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } ``` 客户端: ```java public class ShortConnectionClient { public static void main(String[] args) { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new ClientHandler()); } }); ChannelFuture future = bootstrap.connect("localhost", 8080).sync(); future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } } public class ClientHandler extends SimpleChannelInboundHandler<String> { @Override public void channelActive(ChannelHandlerContext ctx) { // 向服务端发送消息 ctx.writeAndFlush("Hello from client!"); } @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) { // 处理服务端发送的响应 System.out.println("Received message from server: " + msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值