Ecco un semplice esempio che crea un server e un client che si connette a quel server. Ricorda che ciò che invii deve essere un buffer (le stringhe vengono convertite automaticamente in buffer). Il client e il server funzionano indipendentemente l'uno dall'altro, quindi possono essere inseriti nella stessa app o su computer completamente diversi.
Server (server.js):
const net = require("net");
// Create a simple server
var server = net.createServer(function (conn) {
console.log("Server: Client connected");
// If connection is closed
conn.on("end", function() {
console.log('Server: Client disconnected');
// Close the server
server.close();
// End the process
process.exit(0);
});
// Handle data from client
conn.on("data", function(data) {
data = JSON.parse(data);
console.log("Response from client: %s", data.response);
});
// Let's response with a hello message
conn.write(
JSON.stringify(
{ response: "Hey there client!" }
)
);
});
// Listen for connections
server.listen(61337, "localhost", function() {
console.log("Server: Listening");
});
client (Client.js):
const net = require("net");
// Create a socket (client) that connects to the server
var socket = new net.Socket();
socket.connect(61337, "localhost", function() {
console.log("Client: Connected to server");
});
// Let's handle the data we get from the server
socket.on("data", function (data) {
data = JSON.parse(data);
console.log("Response from server: %s", data.response);
// Respond back
socket.write(JSON.stringify({ response: "Hey there server!" }));
// Close the connection
socket.end();
});
I conn
e socket
oggetti sia implementa l'interfaccia Stream
.
Hai provato? Configura due script di nodi in esecuzione su porte separate ... –
Ottengo "Nessun metodo 'connetti'". Non gli piace l'ultima riga lì. – Taurian
Certo che lo è, ma non userei socket.io per quello. Basta usare il modulo 'net'. – mekwall