SpringBoot整合SOCKET 启动成功后Controller失效不能访问的问题。

参考 SpringBoot+SOCKET服务端客户端_jacky 郑的博客-CSDN博客_socket springbootSpringBoot整合SOCKET。

出现问题,项目启动后,无法访问。controller访问不到,提示跨域。

提示 Referrer Policy: strict-origin-when-cross-origin。

解决方法:

经过我的各种测试,发现只要不跟tomcat sprinbgoot的主服务一起启动就没有问题,项目启动后,在用main方法调用socket服务就可以启动,也能收到client发送的请求。

 所以延伸出,使用task定时任务延迟调用启动socket server的方法,发现没问题。成功解决。

 

 

 

粘贴我的代码

定时任务

package com.hs.task;

import com.hs.server.ServerSocketConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;

@Configuration  //标记配置类
@EnableScheduling   //开启定时任务
public class MyScheduleConfig {
    @Autowired
    ServerSocketConfig serverSocketConfig;
    //添加定时任务
    @Scheduled(cron = "0/5 * * * * ?")
    private void myTasks() {
        if(!ServerSocketConfig.isRun){
            System.out.println("执行定时任务 " + LocalDateTime.now());
            serverSocketConfig.socketCreate(7777);
        }else{
            System.out.println("执行定时任务  server 7777 已启动" + LocalDateTime.now());
        }
    }
}

socket server 

package com.hs.server;

import com.hs.service.SenMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * tcp server 启动服务
 */
@Component
public class ServerSocketConfig  {
    @Autowired
    SenMessageService senMessageService;

    private static Logger log = LoggerFactory.getLogger(ServerSocketConfig.class);

    public static ServerSocket serverSocket = null;
    public static boolean isRun = false;

    private static final ThreadPoolExecutor threadpool = new ThreadPoolExecutor(15, 15,
            10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

    public ServerSocketConfig(SenMessageService senMessageService) {
        this.senMessageService = senMessageService;
//        this.socketCreate(7777);
    }

    public  void socketCreate(int port) {
        try {
            serverSocket = new ServerSocket(port);
            log.info("socket服务端开启" + port);
            this.isRun = true;
            while (true){
                Socket socket = serverSocket.accept();
                System.out.println("接收到客户端socket" + socket.getRemoteSocketAddress());
                threadpool.execute(new ServerReceiveThread(socket,senMessageService));
            }
        } catch (IOException e) {
            log.info("socket服务启动异常");
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        socketCreate(7777);
//    }
}

 socket server thread处理的线程

package com.hs.server;

import com.alibaba.fastjson.JSONObject;
import com.hs.conf.Weight;
import com.hs.service.SenMessageService;
import com.hs.util.DateUtilMy;
import com.hs.util.NumberUtils;
import com.hs.util.StringU;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.util.List;

/**
 * tcp server 的线程
 */
public class ServerReceiveThread implements Runnable {

    private Socket socket;
    private SenMessageService senMessageService;

    private static Logger log = LoggerFactory.getLogger(ServerReceiveThread.class);

    public ServerReceiveThread(Socket socket,SenMessageService senMessageService) {
        this.socket = socket;
        this.senMessageService = senMessageService;
    }

    @Override
    public void run() {
        try {
            //获取字节输入流
            InputStream is = socket.getInputStream();
            //将字节输入流转为字符输入流
            InputStreamReader reader = new InputStreamReader(is);
            //将字符输入流包装成缓冲字符输入流
            BufferedReader br = new BufferedReader(reader);
            //循环读取消息
            String msg;
            if ((msg=br.readLine())!=null){
                System.out.println("收到" + socket.getRemoteSocketAddress()+"消息: "+msg);
                String content = msg;
                if(StringU.isEmpity(content)){
                    send(content);
                    log.error("扫码内容为空!");
                    ChuanKou.WARN(null);
                    return;
                }
                //  * ;473-222C228A,B240,40X25,473,Q11,B01,50,10;    |    8999.10
                if(NumberUtils.isNumber(content)){
                    Weight.ZL = Double.valueOf(content);
                    log.info("收到重量" + content);
                }else {
                    log.info("收到扫码字符串:" + content);
                    senMessageService.verify(content);
                }
            }
        } catch (Exception e) {
            log.info(socket.getRemoteSocketAddress()+"下线了");
            e.printStackTrace();
        }
    }

    public void send(String content){
        List<String> list = WebSocketServer.getList();
        if(!StringU.isEmpity(content)){
            list.stream().forEach(sid ->{
                try {
                    WebSocketServer.sendInfo(content + DateUtilMy.getCurrentTime(), sid);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}

客户端

package com.hs.client;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

class TsetTCPClient {
    public static void main(String[] args) throws IOException {
        System.out.println("客户端启动。。。");
        //连接本机端口号7777的程序
        Socket socket=new Socket("127.0.0.1",7777);
        //获取字节输出流
        OutputStream os = socket.getOutputStream();
        //将字节输出流包装成打印流
        PrintStream ps = new PrintStream(os);
        //循环发送消息
        ps.println("500");
    }
}

 

Springboot启动类没有变化 

package com.hs;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@MapperScan("com.hs.dao")
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class PlcXzApplication {

    public static void main(String[] args) {
        SpringApplication.run(PlcXzApplication.class, args);
    }

}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

somdip

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值