के बिना WebSocket मैं चार का उपयोग कर Node.js मैं NodeJS में नौसिखिया हूँ की तरह कुछ बनाने का प्रयास करते हैं और मैं (मैं जानने के लिए यह कैसे काम करता चाहते हैं) socket.io बिना यह बनाना चाहते हैं। यहां कोड है जिसका मैं उपयोग कर रहा हूं।नोड js शुद्ध सॉकेट + 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);
और सभी ठीक काम करते हैं, (मुझे लगता है)। जब मैं स्थानीयहोस्ट खोलता हूं: 7000 मैं नोड सीएमडी संदेशों में "कनेक्ट किए गए" और "कनेक्ट" और "मैं चाक नॉरिस" के बारे में नोड सीएमडी संदेशों में शामिल हूं। उसके बाद मैं ब्राउज़र कंसोल में लिखने कोशिश कर रहा हूँ:
var conn = new WebSocket('ws://localhost:7001/');
इसके अलावा कोई त्रुटि है, लेकिन जब मैं इस लाइन कोशिश कर रहा हूँ: "Uncaught DOMException:
conn.send('lol');
मैं त्रुटि मिल रही है विफल 'वेबस्केट' पर 'प्रेषण' निष्पादित करने के लिए: अभी भी कनेक्टिंग स्थिति में। (...) "
और कुछ समय बाद मुझे एक और त्रुटि मिल रही है:" वेबसॉकेट कनेक्शन 'ws: // localhost: 7001 /' विफल : वेबस्केट ओपनिंग हैंडशेक का समय समाप्त हो गया "
शायद यह कोड गलत है, लेकिन मैंने Google को फेंकने वाली हर चीज को आजमाया है। क्या कोई इस में मेरी मदद कर सकता है?
वेबसॉकेट प्रोटोकॉल बस एक बंदरगाह खोलने से कहीं अधिक जटिल है। यदि आप इसे काम करना चाहते हैं तो आपको सर्वर साइड पर हैंडशेक और फ़्रेमिंग लागू करना होगा। शायद 'ws' लाइब्रेरी देखें। –