send a message to a tcp server in javascript

To send a message from a client to a TCP server in JavaScript, you can use the net module in Node.js. Here's an example code snippet:

index.tsx
const net = require('net');

const client = new net.Socket();

client.connect(8080, 'localhost', function() {
    console.log('Connected to server');
    client.write('Hello, server!');
});

client.on('data', function(data) {
    console.log('Received: ' + data);
    client.destroy(); // kill client after server's response
});

client.on('close', function() {
    console.log('Connection closed');
});
404 chars
18 lines

In this code, we create a new net.Socket object and connect it to the server at 'localhost' on port 8080. Once connected, the client sends the server a message using the write() method.

When the server responds, the client receives the data via the data event, and logs it to the console. Finally, the client destroys the connection with the destroy() method.

gistlibby LogSnag