Skip to content

Instantly share code, notes, and snippets.

@llaine
Created October 15, 2014 19:01
Show Gist options
  • Save llaine/2072f26c3dcde373a141 to your computer and use it in GitHub Desktop.
Save llaine/2072f26c3dcde373a141 to your computer and use it in GitHub Desktop.
WebSocket with NodeJS
var WebSocketClient = require('websocket').client;
var sys = require("sys");
var stdin = process.openStdin();
var client = new WebSocketClient();
client.on('connectFailed', function(error) {
console.log('Connect Error: ' + error.toString());
});
client.on('connect', function(connection) {
console.log('WebSocket client connected');
connection.on('error', function(error) {
console.log("Connection Error: " + error.toString());
});
connection.on('close', function() {
console.log('echo-protocol Connection Closed');
});
connection.on('message', function(message) {
if (message.type === 'utf8') {
var msg = JSON.parse(message.utf8Data);
if(msg.username === undefined) msg.username = "default";
console.log("--> [" + msg.username + "] : "+ msg.txt +"");
}
});
stdin.addListener("data", function(d) {
// note: d is an object, and when converted to a string it will
// end with a linefeed. so we (rather crudely) account for that
// with toString() and then substring()
var msg = d.toString().substring(0, d.length-1);
if(connection.connected){
connection.sendUTF(JSON.stringify({
txt : msg,
username : "console"
}));
}
});
});
client.connect('ws://127.0.0.1:1337/');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<div id="head">
State :
<span id="state"></span>
<br/>
<input type="text" id="name" placeholder="Pseudo" value="webUser">
</div>
<div id="chat">
<input type="text" id="input">
<ul id="messages"></ul>
</div>
</body>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script>
(function($){
var state = $("#state")
, input = $("#input")
, messages = $("#messages")
, username = $("#name");
window.WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('ws://127.0.0.1:1337');
connection.onopen = function () {
// connection is opened and ready to use
state.html("open");
};
connection.onerror = function (error) {
// an error occurred when sending/receiving data
state.html("error ");
input.prop('disabled', true);
username.prop('disabled', true);
};
connection.onmessage = function (message) {
var value = JSON.parse(message.data);
messages.append("<li>" + new Date(message.timeStamp).toDateString() + " | <strong>" + value.username + "</strong> - <pre> " + value.txt +"</pre></li>");
};
input.keydown(function(e){
if(e.keyCode === 13){
var theMsg = $(this).val();
if(!theMsg || !username) return;
var msg = {
txt : theMsg,
username : username.val()
};
connection.send(JSON.stringify(msg));
$(this).val("");
}
})
})(jQuery);
</script>
</html>
(function(){
var WebSocketServer = require('websocket').server;
var http = require('http')
, lesConnexions = [];
var server = http.createServer(function(request, response) {
// process HTTP request. Since we're writing just WebSockets server
// we don't have to implement anything.
});
server.listen(1337/*, function() { }*/);
// create the server
wsServer = new WebSocketServer({
httpServer: server
});
log("Server running on 1337, pending ...");
//log("Connected clients : " + lesConnexions.length);
// WebSocket server
wsServer.on('request', function(request, response) {
var connection = request.accept(null, request.origin);
lesConnexions.push(connection);
log("connection from " + connection.remoteAddress + " | " + lesConnexions.length);
connection.on('message', function(message) {
if(message.type === "utf8"){
for (var i = lesConnexions.length - 1; i >= 0; i--) {
lesConnexions[i].sendUTF(message.utf8Data);
}
}
});
connection.on('close', function(connection) {
lesConnexions.splice(lesConnexions[lesConnexions.length], 1);
log("connection closed");
});
});
function log(item){
console.log("[" + new Date().toDateString() + "] " + item);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment