我想用node.js創建類似char的東西 我是nodejs的新手,我想在沒有socket.io的情況下創建它(我想了解它是如何工作的)。 這是我使用的代碼。node js net sockets + websocket without 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我收到有關「連接到:」和「連接」和「我是查克諾里斯」的節點CMD消息。 後,我在瀏覽器控制檯嘗試寫:
var conn = new WebSocket('ws://localhost:7001/');
而且沒有錯誤,但是當我試圖這樣一行:
conn.send('lol');
我得到錯誤:「未捕獲拋出:DOMException:失敗在'WebSocket'上執行'發送':仍處於連接狀態(...)「
並且經過一段時間後,我又收到一個錯誤:」WebSocket連接到'ws:// localhost:7001 /'失敗:WebSocket打開握手超時「
也許這個代碼是錯誤的,但我已經嘗試了所有我發現拋出谷歌。有人可以幫我弄這個嗎?
WebSocket協議比打開一個端口複雜得多。如果你想要這個工作,你必須在服務器端實現握手和成幀。查看'ws'庫,也許。 –