java实现BIO服务器端网络编程(在springboot中使用)

  1. 创建一个类BIOServer
@Component
public  class BioServer {
    @Autowired
    AsyncService asyncService;

    public ServerSocket  serverSocket = null;
    public  void BioServerListen() throws IOException {
        try{
            serverSocket = new ServerSocket(8888);
            System.out.println("服务启动了");
            while(true){
                //监听,等待客户端连接
                final Socket socket = serverSocket.accept();
                System.out.println("连接到一个客户端");
                //创建一个线程,与之通信
                asyncService.dataHandler(socket);
            }
        }catch (IOException exception){

        }
    }
}
  1. AsyncService(为了偷懒没有接口+实现类的形式),调用其中使用了 异步方法处理,从而实现多线程可连接多个客户端
package com.mql.nettybio.BioServer;


import com.mql.nettybio.mapper.AdcpMapper;
import com.mql.nettybio.bean.ADCP_DataInfo;
import com.mql.nettybio.config.GetDataInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.text.ParseException;


@Component
public class AsyncService {
    @Autowired
    AdcpMapper adcpMapper;//mapper接口,可忽略

	//日志操作,可忽略
    private Logger logger = Logger.getLogger(AsyncService.class);

	//开启异步方法的注解 里面的名字将于下文中的Bean实例名字必须相同
    @Async("asyncServiceExecutor")
    public void dataHandler(Socket socket){
        System.out.println("Spring自带的线程池" + Thread.currentThread().getName());
         InputStream inputStream = null;
        try {
            byte[] bytes = new byte[1024];
            inputStream = socket.getInputStream();
            while(true){
                int read = inputStream.read(bytes);
                if(read!=-1){
                    String dataTemp = new String (bytes,0,read,"GBK");

                    logger.info(dataTemp);
					//这里是我获取到数据添加到数据库,可忽略
                    /*ADCP_DataInfo dataInfo = GetDataInfo.getDataInfo(dataTemp.trim());

                    if(dataInfo!=null){
                        if(adcpMapper.insertDataInfo(dataInfo)==1){
                            logger.info("新增成功");
                        }else {
                            logger.info("新增失败");
                        }
                    }else {
                        logger.info("无效数据");
                    }*/

                }else {
                    break;
                }
            }


        } catch (IOException | ParseException exception) {
            exception.printStackTrace();
            logger.error(exception);
        }finally {
            System.out.println("关闭和client的连接");
            logger.info("关闭和client的连接");
            try{
                if(inputStream!=null){
                    inputStream.close();
                }
            }catch (Exception exception){
                exception.printStackTrace();
            }

            try{
                if(socket!=null){
                    socket.close();
                }
            }catch (Exception exception){
                exception.printStackTrace();
            }
        }
    }
}

  1. 异步线程的配置类
package com.mql.nettybio.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ExecutorConfig {


    @Bean //asyncServiceExecutor与上文中的注解中名字相同
    public Executor asyncServiceExecutor() {

        //申请一个线程池 threadPoolTas
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(5);
        //配置最大线程数
        executor.setMaxPoolSize(10);
        //配置队列大小
        executor.setQueueCapacity(99999);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("async-service-");

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}
  1. 在SpiringBoot启动类中调用
package com.mql.nettybio;

import com.mql.nettybio.BioServer.BioServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.io.IOException;

@SpringBootApplication

@EnableScheduling  //表示开启异步线程使用(不可省略),会导致异步方法无法起作用
public class NettyBioApplication {


    public static void main(String[] args) throws IOException {
        SpringApplication.run(NettyBioApplication.class, args).getBean(BioServer.class).BioServerListen();
        //这里不能用new BioServer() 去调用BioServerListen(); 因为new出来的实例没有被ioc容器接管,会报错
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值