const net=require('net');
function processTcpPayload(data,sock){
console.log(data.toString('ascii'));
}
const startTCPServer = ()=>{
try{
net.createServer((sock)=>{
sock.on('data',
(data)=>{
processTcpPayload(data,
sock);
});
sock.on('error',
(err)=>{
});
sock.on('close',
(data)=>{
});
}).listen(portHere,
ipHere);
}catch(err){
}process.on('SIGINT',
()=>{
process.exit(0);
});
};
I have create a TCP Server using Nodejs. I wanted to connect my react application to this TCP Server and send data to it. I wrote the React code using 'socket.io-client' and sent the event to the server. But all I can see on the NodeJS Server is the following data
GET /socket.io/?EIO=4&transport=websocket HTTP/1.1 Host: HOSTIP:HOSTPORT Connection: Upgrade Pragma: no-cache Cache-Control: no-cache User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Upgrade: websocket Origin: http://ipWasHere:PORT_WAS_HERE Sec-WebSocket-Version: 13 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9 Cookie: languageId=eng Sec-WebSocket-Key: WEBSOCKET_KEY_WAS_HERE Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
My ReactJs is code is as following:
import { io } from "socket.io-client";
const socket = io.connect("http://TCPSERVERIP:TCPSERVERPORT", {
transports: ["websocket"],
});
useEffect(() => {
socket.on("message", (data) => {
alert(JSON.stringify(data));
});
socket.emit("data", { message: "DATA IS HERE" });
// socket.emit("message", { message: "DATA IS HERE" });
}, []);
I understand that Web-sockets are layered over HTTP, so this is somewhat expected behavior. But I cannot find the solution to this dilemma. Can I not communicate directly using TCP on React and NodeJS? Or do I need to shift to a websocket server on my NodeJs Service?