Sto cercando di creare qualcosa come char usando node.js Sono novizio in nodejs e voglio crearlo senza socket.io (voglio imparare come funziona). Ecco il codice che sto usando.nodo js prese di rete + web socket senza socket.io
var http = require('http');
var net = require('net');
var server = http.createServer(function(req,res){
res.writeHead(200,{'content-type' : 'text/html'});
res.write('<a href="./lol/">lol</a><br>');
res.end('hello world: '+req.url);
var client = new net.Socket();
client.connect('7001', '127.0.0.1', function() {
console.log('CONNECTED TO: ');
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('I am Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
//req.
});
server.listen(7000);
require('net').createServer(function (socket) {
console.log("connected");
socket.on('data', function (data) {
console.log(data.toString());
});
}).listen(7001);
E tutto funziona bene, (penso). Quando sono aperto localhost: 7000 sto ricevendo messaggi di nodo CMD su "CONNECTED TO:" e "connected" e "I am Chack Norris". Dopo di che sto cercando di scrittura nella console del browser:
var conn = new WebSocket('ws://localhost:7001/');
Inoltre nessun errore, ma quando sto cercando questa linea:
conn.send('lol');
sto ottenendo l'errore: "DOMException Uncaught: Failed per eseguire "invia" su "WebSocket": ancora in stato CONNESSIONE. (...) "
E dopo un po 'di tempo ricevo un altro errore:" Connessione WebSocket a "ws: // localhost: 7001 /" non riuscita : Scaduto l'handshake di apertura WebSocket "
forse questo codice è sbagliato, ma ho provato tutto ciò che ho trovato gettare il google. Qualcuno può aiutarmi con questo?
Il protocollo WebSocket è molto più complicato della semplice apertura di una porta. Devi implementare l'handshake e il framing sul lato server se vuoi che funzioni. Controlla la libreria 'ws', forse. –