首页 文章

使用Spring Boot Web的TCP套接字客户端

提问于
浏览
0

我正在使用Spring Boot Web开发Web应用程序,我想使用IP和端口(连接,发送,接收和断开)与TCP套接字服务器进行通信 .

我是Spring Boot的新手,我在网上搜索了很多天没有任何工作结果,而Websocket解决方案在这种情况下不起作用 .

更新(请确认)我认为我可以像任何其他Java程序一样使用Spring Boot Web juste中的标准java.io. *和java.net . *:

try {
            try (Socket clientSocket = new Socket(IP, PORT);
                PrintWriter out = new PrintWriter(
                        clientSocket.getOutputStream(), true);
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                clientSocket.getInputStream()))) {

            System.out.println("Connected to server");

            String str = "test";                                
            out.write(str);
            out.flush();

            char[] cbuf = new char[size];            
            br.read(cbuf, 0, size);
            System.out.println(cbuf);

        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

1 回答

  • 0

    这是我为SpringBoot开发的简单tcp客户端的自己版本 .

    首先,您必须使用openConnection()方法打开连接 . 然后,您可以使用sendMessage()方法发送消息,并使用takeMessage()方法接收消息 .

    @Service("socketClient")
    
    public class SocketClient {
        @Value("brain.connection.port")
        int tcpPort;
        @Value("brain.connection.ip")
        String ipConnection;
        private Socket clientSocket;
    
        private DataOutputStream outToTCP;
        private BufferedReader inFromTCP;
    
        private PriorityBlockingQueue<String> incomingMessages = new PriorityBlockingQueue<>();
        private PriorityBlockingQueue<String> outcomingMessages = new PriorityBlockingQueue<>();
    
        private final Logger log = LoggerFactory.getLogger(this.getClass());
    
        private Thread sendDataToTCP = new Thread(){
            public void run(){
                String sentence = "";
                log.info("Starting Backend -> TCP communication thread");
                while(true){
                    try {
                        sentence = incomingMessages.take();
                        outToTCP.writeBytes(sentence + '\n');
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
            }
        };
    
        private Thread getDataFromTCP = new Thread(){
            public void run(){
                log.info("Starting TCP -> Backend communication thread");
                while(true){
                    String response = "";
                    try {
                        response = inFromTCP.readLine();
                        if (response == null)
                            break;
                        outcomingMessages.put(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    
        public void openConnection(){
            try {
                this.clientSocket = new Socket(ipConnection, tcpPort);
                outToTCP = new DataOutputStream(clientSocket.getOutputStream());
                inFromTCP = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                getDataFromTCP.start();
                sendDataToTCP.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //Send messages to Socket.
        public void sendMessage(String message) throws InterruptedException {
            incomingMessages.put(message);
        }
        //Take Message from Socket
        public String takeMessage() throws InterruptedException {
            return outcomingMessages.take();
        }
    }
    

相关问题