Created
December 16, 2014 19:02
-
-
Save mayfer/977f2e010a388f82f773 to your computer and use it in GitHub Desktop.
Node, Websockets (socket.io), Prototypical inheritance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype> | |
<html> | |
<head> | |
<title>hi</title> | |
<style> | |
body, html { | |
background: #aaa; | |
font-family: monospace; | |
} | |
</style> | |
<script src="/socket.io/socket.io.js"></script> | |
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> | |
<script> | |
var ParentClassThing = function() { | |
return this; | |
} | |
ParentClassThing.prototype.shared_method = function() { | |
console.log("SHARED!"); | |
} | |
var Main = function() { | |
console.log(this); | |
var local = function() { | |
console.log("LOCAL!"); | |
} | |
this.init_network = function() { | |
this.socket = io(); | |
console.log(this) | |
this.socket.on("murat", function(msg){ | |
$('body').append(msg).append('<br />'); | |
}); | |
local(); | |
} | |
this.init_ui = function() { | |
var socket = this.socket; | |
$('form').submit(function(e){ | |
e.preventDefault(); | |
var msg = $('input[name="message"]').val(); | |
socket.emit("murat", msg); | |
$('input[name="message"]').val(''); | |
$('body').append(msg).append('<br />'); | |
}); | |
} | |
return this; | |
} | |
Main.prototype = ParentClassThing.prototype; | |
$(document).ready(function(){ | |
var main = new Main(); | |
main.init_network(); | |
main.init_ui(); | |
main.shared_method(); | |
}); | |
</script> | |
</head> | |
<body> | |
<form> | |
<input type='text' name='message' /> | |
<input type='submit' name='asd' value='Send' /> | |
</form> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// now using express to handle routing | |
var express = require('express'); | |
var app = express(); | |
var http = require('http').Server(app); | |
var io = require('socket.io')(http) | |
var path = require('path'); | |
app.get('/', function(req, res){ | |
res.sendFile(path.join(__dirname, 'ws.html')); | |
}); | |
http.listen(8888, function(){ | |
console.log('listening on *:8888'); | |
}); | |
app.use(express.static(__dirname)); | |
io.on('connection', function(socket){ | |
console.log(socket.id); | |
console.log('a user connected'); | |
socket.on('murat', function(msg){ | |
console.log('message to murat', msg); | |
setTimeout(function() { | |
socket.broadcast.emit("murat", msg); | |
}, 2000); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment