私は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);
すべてうまく動作します(私は思う)。 私はlocalhostを開いている:7000私は、 "接続された"と "接続された"と "私はチャックノリスです"というノードのCMDメッセージを受け取っています。 その後、私は、ブラウザのコンソールに書き込みをしようとしている。また
var conn = new WebSocket('ws://localhost:7001/');
エラーなし、しかし、私はこの行をしようとしているとき:
conn.send('lol');
私はエラーになっている:「キャッチされない例外:DOMException:失敗実行するためには、「WebSocketを」オン「に送信」:それでも接続状態で(...)「
そして、いくつかの時間後に私は1つの以上のエラーを取得しています:」。 『WS:// localhostを:7001 /』へのWebSocket接続が失敗しました:WebSocketオープニングハンドシェイクタイムアウト "
多分このコードは間違っていますが、私は私がgoogleを見つけたすべてのものを試しました。誰かがこれで私を助けることができますか?
WebSocketプロトコルは、単にポートを開くよりもはるかに複雑です。これを動作させたい場合は、サーバ側でハンドシェイクとフレーミングを実装する必要があります。おそらく 'ws'ライブラリをチェックしてください。 –