'How to connect to simple tcp socket in React
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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | natalia ortega |