1

I'm developing a web application using Spring Boot Web and I want to communicate with a TCP socket server using IP and Port (connect, send, receive and disconnect).

I'm new to Spring Boot and I searched many days in the internet without any working result and the Websocket solution will not work in this case.

UPDATE (please confirm) I think that I can use the standard java.io.* and java.net.* in Spring Boot Web juste like any other Java Program:

    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();
    }
Hicham
  • 41
  • 1
  • 2
  • 6

1 Answers1

0

This is my own version of a simple tcp client developed for SpringBoot.

First, you have to open the connection with the openConnection() method. Then, you can send messages with sendMessage() method and receive messages with takeMessage() method.

@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();
    }
}
cbadillac
  • 1
  • 1