【IDEA】基于IO、NIO、Netty的TCP网络聊天程序

本文详细介绍了如何使用IO、NIO和Netty三种方式实现TCP聊天程序,对比了它们的特点和差异。IO基于阻塞IO模型,适合短连接,而NIO引入了选择器,实现单线程处理多个连接。Netty作为高性能的异步网络通信框架,提供了更高级别的抽象。通过实例代码展示了每种方式的实现过程,并进行了测试验证。

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

一、IO实现TCP聊天程序

1. IO简介

  1. 服务端阻塞点
server.accept();获取套接字的时候
inputStream.read(bytes);输入流读取数据的时候
  1. 传统socket是短连接,可以做短连接服务器,他无法做长连接,属于一问一答的模式,比如老的tomcat底层用的就是socket,用完就会关掉线程,因此不会出现线程一直被占用的情况,支持处理多个客户端连接。
    (1)单线程情况下只能有一个客户端(一个线程维护一个连接,也就是一个socket客户连接)线程一直被占用。
    (2)用线程池可以有多个客户端连接,但是非常消耗性能(用此案城池,就是老tomcat原理,只不过是用完后就释放)

2. IO实现网络程序

  • 新建两个java项目(一个Server端,一个client端)
    在这里插入图片描述
  • Server端代码编写
package com.company;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.io.InputStream;
import java.net.Socket;

public class Main {

    public static void main(String[] args)  throws IOException {
        //创建客户端的Socket对象(SevereSocket)
        //ServerSocket (int port)创建绑定到指定端口的服务器套接字
        ServerSocket ss = new ServerSocket(50000);

        //Socket accept()侦听要连接到此套接字并接受他
        Socket s = ss.accept();

        //获取输入流,读数据,并把数据显示在控制台
        InputStream is = s.getInputStream();
        byte[] bys = new byte[1024];
        int len = is.read(bys);
        String data = new String(bys, 0, len);
        System.out.println("数据是:" + data);

        //释放资源
        s.close();
        ss.close();
    }
}

在这里插入图片描述

  • Client端代码编写
package com.company;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class Main {

    public static void main(String[] args) throws IOException {
        //创建客户端的Socket对象
        //Socket (InetAddress adress,int port)创建流套接字并将其连接到指定IP地址的指定端口号
//		Socket s=new Socket(InetAddress.getByName("192.168.224.1"), 10000);
        //Socket (String host,int port)创建流套接字并将其连接到指定主机的指定端口号
        Socket s=new Socket("127.0.0.1", 50000);

        //获取输出流,写数据
        //OutputStream getOutputStream();返回此套接字的输出流
        OutputStream os=s.getOutputStream();
        os.write("hello,tcp".getBytes());

        //释放资源
        s.close();
    }
}

在这里插入图片描述

3. 运行测试

在这里插入图片描述
测试成功。

二、NIO实现TCP聊天程序

1. NIO简介

  1. NIO特点
      NIO单线程模型,采用selector管理的轮询查询模式,selector每隔一段时间都去看一下client端有没有产生需要处理的消息(客户端连接请求、客户端发送数据请求、客户端下载数据请求),也就是说selector会同时管理client端的连接和通道内client端的读、写请求。
      NIO单线程模型:采用selector管理的轮询查询模式,selector每隔一段时间都去看一下client端有没有产生需要处理的消息(客户端连接请求、客户端发送数据请求、客户端下载数据请求),也就是说selector会同时管理client端的连接和通道内client端的读、写请求。

  2. NIO与IO的主要区别
    在这里插入图片描述

2. NIO实现网络程序

  • 新建两个java项目(一个Server端,一个client端)
    在这里插入图片描述
  • Server端代码编写
package com.company;

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 Main {

    //网络通信IO操作,TCP协议,针对面向流的监听套接字的可选择通道(一般用于服务端)
    private ServerSocketChannel serverSocketChannel;
    private Selector selector;

    /*
     *开启服务端
     */
    public void start(Integer port) throws Exception {
        serverSocketChannel = ServerSocketChannel.open();
        selector = Selector.open();
        //绑定监听端口
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        //设置为非阻塞模式
        serverSocketChannel.configureBlocking(false);
        //注册到Selector上
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        startListener();
    }
    private void startListener() throws Exception {
        while (true) {
            // 如果客户端有请求select的方法返回值将不为零
            if (selector.select(1000) == 0) {
                System.out.println("current not exists task");
                continue;
            }
            // 如果有事件集合中就存在对应通道的key
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            // 遍历所有的key找到其中事件类型为Accept的key
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable())
                    handleConnection();
                if (key.isReadable())
                    handleMsg(key);
                iterator.remove();
            }
        }
    }
    /**
     * 处理建立连接
     */
    private void handleConnection() throws Exception {
        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
    }
    /*
     * 接收信息
     */
    private void handleMsg(SelectionKey key) throws Exception {
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer attachment = (ByteBuffer) key.attachment();
        channel.read(attachment);
        System.out.println("current msg: " + new String(attachment.array()));
    }

    public static void main(String[] args) throws Exception {
        Main myServer = new Main();
        myServer.start(8888);
    }
}

在这里插入图片描述

  • Client端代码编写
package com.company;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Main {

    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        // 连接服务器
        if (!socketChannel.connect(new InetSocketAddress("127.0.0.1", 8888))) {
            while (!socketChannel.finishConnect()) {
                System.out.println("connecting...");
            }
        }
        //发送数据
        String str = "hello netty";
        ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
        socketChannel.write(byteBuffer);
        System.in.read();
    }
}

在这里插入图片描述

3. 运行测试

在这里插入图片描述
测试成功。

三、Netty实现TCP聊天程序

1. Netty简介

  1. Netty定义
     Netty 是一个基于NIO的客户、服务器端编程框架。
  2. Netty特点
    (1)使用Netty 可以确保你快速和简单的开发出一个网络应用。
    (2)Netty 是一个吸收了多种协议的实现经验,包括FTP,SMTP,HTTP,各种二进制,文本协议,并经过相当精心设计的项目。
    (3)Netty在保证程序易于开发的同时,还保证了应用的高性能,稳定性和伸缩性。

2. Netty实现网络程序

  • 新建两个java项目(一个Server端,一个client端),并导入jar
    在这里插入图片描述
    • Server端代码编写
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 *
 */
public class Server {

    private int port;

    public static void main(String[] args){
        new Server(18080).start();
    }

    public Server(int port) {
        this.port = port;
    }

    public void start() {
        /**
         * 创建两个EventLoopGroup,即两个线程池,boss线程池用于接收客户端的连接,
         * 一个线程监听一个端口,一般只会监听一个端口所以只需一个线程
         * work池用于处理网络连接数据读写或者后续的业务处理(可指定另外的线程处理业务,
         * work完成数据读写)
         */
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup work = new NioEventLoopGroup();
        try {
            /**
             * 实例化一个服务端启动类,
             * group()指定线程组
             * channel()指定用于接收客户端连接的类,对应java.nio.ServerSocketChannel
             * childHandler()设置编码解码及处理连接的类
             */
            ServerBootstrap server = new ServerBootstrap()
                    .group(boss, work).channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast("decoder", new StringDecoder())
                                    .addLast("encoder", new StringEncoder())
                                    .addLast(new HelloWorldServerHandler());
                        }
                    });
            //绑定端口
            ChannelFuture future = server.bind().sync();
            System.out.println("server started and listen " + port);
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }

    public static class HelloWorldServerHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("HelloWorldServerHandler active");
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("server channelRead..");
            System.out.println(ctx.channel().remoteAddress()+"->Server :"+ msg.toString());
            ctx.write("server write"+msg);
            ctx.flush();
        }
    }
}

在这里插入图片描述

  • Client端代码编写
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 *
 */
public class Client {
    private static final String HOST = "localhost";
    private static final int PORT= 18080;

    public static void main(String[] args){
        new Client().start(HOST, PORT);
    }

    public void start(String host, int port) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap client = new Bootstrap().group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast("decoder", new StringDecoder())
                                    .addLast("encoder", new StringEncoder())
                                    .addLast(new HelloWorldClientHandler());
                        }
                    });
            ChannelFuture future = client.connect(host, port).sync();
            future.channel().writeAndFlush("Hello Netty Server ,I am a netty client");
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();

        }

    }

    public static class HelloWorldClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("HelloWorldClientHandler Active");
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("HelloWorldClientHandler read Message:"+msg);
        }
    }
}

在这里插入图片描述

3. 运行测试

在这里插入图片描述
测试成功!

四、总结

  本文对IO、NIO、Netty的进行了简单介绍,并分别基于IO、NIO、Netty编写了TCP网络聊天程序。

五、参考

https://blog.youkuaiyun.com/junseven164/article/details/121714791?spm=1001.2014.3001.5501

Exception in thread "Thread-23" java.net.BindException: Address already in use: bind at java.base/sun.nio.ch.Net.bind0(Native Method) at java.base/sun.nio.ch.Net.bind(Net.java:461) at java.base/sun.nio.ch.Net.bind(Net.java:453) at java.base/sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:227) at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:141) at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:562) at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1334) at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:600) at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:579) at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:973) at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:260) at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:380) at io.netty.util.concurrent.AbstractEventExecutor.runTask$$$capture(AbstractEventExecutor.java:173) at io.netty.util.concurrent.AbstractEventExecutor.runTask(AbstractEventExecutor.java) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute$$$capture(AbstractEventExecutor.java:166) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:470) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:569) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Thread.java:834)
最新发布
03-18
<think>好的,我现在需要解决用户提出的Java程序中出现的java.net.BindException: Address already in use异常,特别是在使用Netty框架时的情况。首先,我得理解这个异常的原因。根据用户提供的引用内容,这个错误通常是因为端口被占用导致的。但可能还有其他原因,比如TCP连接数限制或短暂的端口占用。 首先,我应该考虑常见的解决方案,比如查找并终止占用端口的进程。用户提到的引用[1]、[2]、[3]都提到了这一点。可以通过命令行工具如netstat或lsof来找到占用端口的进程,然后结束它。如果是Windows系统,可能需要用不同的命令,比如netstat -ano | findstr <端口号>,然后使用taskkill结束进程。 接下来,可能需要调整端口释放时间,如引用[4]提到的Windows的MaxUserPort和TCPTimedWaitDelay设置。这适用于大量短连接导致端口耗尽的情况,而不仅仅是单个端口被占用。如果用户的应用需要处理高并发连接,调整这些系统参数可能有效。 另外,Netty本身是否有配置可以重用地址?比如设置SO_REUSEADDR选项。这可能允许端口在TIME_WAIT状态下被重新绑定,避免等待时间。引用中没有提到这点,但根据Netty的文档,可以在ServerBootstrap中设置channelOption(ChannelOption.SO_REUSEADDR, true)。 还有可能用户代码中存在多次绑定同一端口的情况,比如没有正确关闭之前的服务器实例。需要检查代码逻辑,确保在关闭或重新绑定前释放资源。 此外,检查防火墙或安全软件是否干扰端口的使用,虽然引用里没提到这点,但也是可能性之一。暂时可能不作为主要解决方案,但可以作为备选建议。 最后,如果是短时大量连接导致端口耗尽,除了调整系统参数,还可以优化代码,比如使用连接池或减少频繁创建连接。这在Netty中可能需要优化Channel的处理方式。 现在需要将这些思路整理成结构化的步骤,确保覆盖所有可能的解决方案,并引用用户提供的资料中的相关内容。同时,要使用中文,按照用户的要求分步骤说明,并生成相关问题。</think>### 解决Java程序中`java.net.BindException: Address already in use`异常(Netty场景) #### 1. **确认端口占用并终止进程** - **查找占用端口的进程**: ```bash # Linux/Mac lsof -i :<端口号> # Windows netstat -ano | findstr <端口号> ``` 根据结果获取进程ID(PID),使用`kill -9 <PID>`(Linux/Mac)或`taskkill /PID <PID> /F`(Windows)终止进程[^1][^2][^3]。 - **常见场景**:开发时IDE未正确关闭服务(如IntelliJ IDEA)导致端口残留。 #### 2. **调整Netty的SO_REUSEADDR选项** -Netty服务端代码中启用端口重用(避免`TIME_WAIT`状态阻塞): ```java ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.option(ChannelOption.SO_REUSEADDR, true); // 允许绑定到处于TIME_WAIT的端口 ``` 此配置可减少因端口未释放导致的绑定失败。 #### 3. **优化系统TCP连接参数(Windows场景)** - **问题根源**:Windows默认最大TCP连接端口数(`MaxUserPort=5000`)及端口释放时间(`TCPTimedWaitDelay=240秒`),短时高并发可能导致端口耗尽[^4]。 - **解决方案**: 1. 修改注册表(需重启): ```bash # 增大最大端口数 reg add HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters /v MaxUserPort /t REG_DWORD /d 65534 # 缩短端口释放时间 reg add HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters /v TCPTimedWaitDelay /t REG_DWORD /d 30 ``` 2. 调整Netty连接池或减少短连接的频繁创建。 #### 4. **检查代码逻辑错误** - **重复绑定**:确保`ServerBootstrap`仅绑定一次,避免因异常重试或逻辑错误导致多次绑定。 - **资源未释放**:在关闭Netty服务时调用`ChannelFuture.channel().closeFuture().sync()`确保完全释放端口。 #### 5. **其他可能性** - **防火墙/安全软件拦截**:临时关闭防火墙或添加端口白名单。 - **容器化环境冲突**:如Docker运行时端口映射错误(需检查`docker run -p`参数)[^3]。 --- ### 示例代码(Netty服务端绑定优化) ```java public class NettyServer { public void start(int port) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_REUSEADDR, true) // 关键配置 .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { // 添加业务处理逻辑 } }); ChannelFuture future = bootstrap.bind(port).sync(); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值