Spaces:
Running
Running
File size: 1,635 Bytes
8f3f8db |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
var http = require("http");
var ws = require("ws");
var readline = require('readline');
function startServer(port) {
// Create HTTP server
var httpServer = new http.createServer();
// Create WebSocket server
var webSocketServer = new ws.Server({ noServer: true });
webSocketServer
.on("connection", function(ws) {
console.log("Connection made.");
// Allow interaction on connection
var io = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var handleIO = function() {
io.question("Next command: ", function(command) {
if (command) {
isClosed = isClosed || [ "quit", "exit", "bye" ].indexOf(command) >= 0;
if (!isClosed) {
ws.send(command);
} else {
ws.close();
io.close();
}
} else {
handleIO();
}
});
};
// Handle events
var isClosed = false;
ws
.on("message", function(message) {
console.log("Message received: " + message);
handleIO(); // Do next command
})
.on("close", function(code) {
console.log("Connection closed: " + code);
isClosed = true;
io.close();
})
;
// Send first command (will trigger IO handling)
ws.send("3 + 4");
})
;
// Start HTTP server
httpServer.on("upgrade", function(request, socket, head) {
console.log("Upgrading");
webSocketServer.handleUpgrade(request, socket, head, function(ws) {
webSocketServer.emit("connection", ws, request);
});
});
httpServer.listen(9000);
};
console.log("Starting WebSocketServer on port 9000");
console.log("Waiting on clients to connect...");
startServer();
|