我最初使用此Websocket/node tutorial作为起点。这是我的第一次尝试,所以当我开始时几乎什么都不知道。
"连接关闭......握手"这是一个非常普遍的问题,似乎没有明确的答案。从许多SO问题我花了一天时间尝试答案和建议代码,没有效果,包括检查我的代理和允许localhost(没有快乐)。
这是我的代码,包括一个(不完整的)前端(我在我的本地目录中使用npm install websocket
,而不是使用socket.io,虽然我愿意尝试我&# 39; d宁愿让这个先工作一下):
"use strict";
let http = require('http');
let fs = require('fs');
let server = http.createServer(function(request, response) {});
const PORT=8080;
fs.readFile('client/index.html', function (err, html) {
if (err) throw err;
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
console.log(`${(new Date())} Server is listening on port ${PORT}`);
}).listen(PORT);
});
let WebSocketServer = require('websocket').server;
let wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(r){
// runs on connection
let connection = r.accept('echo-protocol', r.origin);
let count = 0;
let clients = {};
// Specific id for this client & increment count
let id = count++;
// Stores the connection method for looping through & contacting all clients
clients[id] = connection;
console.log(`${(new Date())} Connection accepted [${id}]`);
connection.on('message', function(message) {
// The string message sent to us
let msgString = message.utf8Data;
// Loops through all clients
for(let i in clients){
// Sends a message to the client with the message
clients[i].sendUTF(msgString);
}
});
connection.on('close', function(reasonCode, description) {
delete clients[id];
console.log(`${(new Date())} Peer ${connection.remoteAddress} disconnected.`);
});
});
<body>
<h1>Hello Web Sockets</h1>
<div id="chatlog"></div>
<input type="text" id="message">
<input type="button" value="Send" onclick="sendMessage()">
<!-- lose 'onclick' later -->
<script>
"use strict";
let ws = new WebSocket('ws://localhost:8080', 'echo-protocol');
function sendMessage(){
console.log(ws);
let message = document.getElementById('message').value;
console.log(message);
ws.send(message);
}
ws.addEventListener('message', function(e){
// The data is the message being sent back
let msg = e.data;
// Append the message to the DOM
document.getElementById("chatlog").innerHTML += `<br>${msg}`;
});
</script>
</body>