0

I am new to React and can't seem to find any example regarding how to create a simple TCP connection to receive data from the other server (NOT via websocket).

For example, I want to start a listener on Linux with netcat on port 3333:

nc -k -l localhost 3333

and I want to have my react app connect to this port and receive plain some text back. It would be good to have timer reconnect feature in case the other side is not up for connecting yet. I am not sure if the socket.io-client library is capable of connecting to a plain tcp socket (not websocket protocol).

import React, { useState, useEffect } from 'react';

const io = require('socket.io-client');
const socket = io('localhost:3333');

function App() {
  const [messageCount, setMessageCount] = useState(0);
 
  useEffect(() => {
    socket.on('receive message', payload => {
      setMessageCount(messageCount + 1);
    });
  }, []);
  
  return (
     <div class="theme-1">
       <p>received {messageCount} messages</p>
     </div>
  );
}

export default App;

Any help is appreciated. Thanks.

freedo
  • 105
  • 1
  • 7
  • Does this answer your question? https://stackoverflow.com/questions/52125356/create-tcp-ip-socket-in-client-side-javascript and https://stackoverflow.com/questions/12407778/connecting-to-tcp-socket-from-browser-using-javascript – Lin Du Nov 23 '21 at 06:33
  • Ok, so I take it that it is not supported due to security concerns. In that case, one way to get around this would be to write a server side process to process incoming TCP data on one side and then relay it onto my react process via websocket interface? Not sure if there are other ways to achieve what I wanted to do. – freedo Nov 23 '21 at 15:20

1 Answers1

0

In order to connect via react, one must implement three-way handshake on server side referencing a specified port, is primarily used to create a TCP socket connection to reliably transmit data between devices.

More information check -> Implement 3 way handshake for TCP in Java