Oto prosty przykład, który tworzy serwer i klienta, który łączy się z tym serwerem. Pamiętaj, że to, co wysyłasz, musi być buforem (łańcuchy są automatycznie konwertowane na bufory). Klient i serwer działają niezależnie od siebie, dlatego można je umieścić w tej samej aplikacji lub na zupełnie innych komputerach.
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");
});
klienckie (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();
});
W conn
socket
i oba obiekty implementować interfejs Stream
.
Czy próbowałeś? Skonfiguruj dwa skrypty na węźle działające na oddzielnych portach ... –
Otrzymuję komunikat "Nie ma metody" connect "". Nie podoba mu się ostatnia linia. – Taurian
Oczywiście, że tak, ale nie użyłbym do tego socket.io. Po prostu użyj modułu 'net'. – mekwall