Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Adding additional files

  • Loading branch information...
commit b0c760178304c594216d6cbba95b6353186c45bd 1 parent 610b280
@jpf authored
View
64 sessions/hour2/04_socket-io-a-primer/index.html
@@ -1,19 +1,55 @@
-<!DOCTYPE html>
-<html>
-<head>
-<title> </title>
<script src="/socket.io/socket.io.js"></script>
-<script type="text/javascript">
+<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
+<script>
+ var socket = io.connect();
- var socket = io.connect();
- socket.on('news', function (data) {
- console.log(data);
- socket.emit('my other event', { my: 'data' });
+ // NOTE: This connection will take a while to build on servers that don't support WebSockets.
+ // For an example of how to handle servers that don't support WebSockets, see the section titled "Windows Azure Considerations" on this page: http://www.windowsazure.com/en-us/develop/nodejs/tutorials/app-using-socketio/
+ // on connection to server, ask for user's name with an anonymous callback
+ socket.on('connect', function(){
+ // call the server-side function 'adduser' and send one parameter (value of prompt)
+ socket.emit('adduser', prompt("What's your name?"));
+ });
+
+ // listener, whenever the server emits 'updatechat', this updates the chat body
+ socket.on('updatechat', function (username, data) {
+ $('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
+ });
+
+ // listener, whenever the server emits 'updateusers', this updates the username list
+ socket.on('updateusers', function(data) {
+ $('#users').empty();
+ $.each(data, function(key, value) {
+ $('#users').append('<div>' + key + '</div>');
});
+ });
-</script>
-</head>
-<body>
+ // on load of page
+ $(function(){
+ // when the client clicks SEND
+ $('#datasend').click( function() {
+ var message = $('#data').val();
+ $('#data').val('');
+ // tell server to execute 'sendchat' and send along one parameter
+ socket.emit('sendchat', message);
+ });
-</body>
-</html>
+ // when the client hits ENTER on their keyboard
+ $('#data').keypress(function(e) {
+ if(e.which == 13) {
+ $(this).blur();
+ $('#datasend').focus().click();
+ }
+ });
+ });
+
+</script>
+<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
+ <b>USERS</b>
+ <div id="users"></div>
+</div>
+<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
+ <div id="conversation"></div>
+ <input id="data" style="width:200px;" />
+ <input type="button" id="datasend" value="send" />
+</div>
View
133 sessions/hour2/04_socket-io-a-primer/readme.md
@@ -65,114 +65,81 @@ Socket.io works by piggybacking onto your existing HTTP server instance to
listen for incoming connections and messages from clients.
```javascript
-var http = require('http');
-var socketio = require('socket.io');
-var fs = require('fs');
-
-var app = http.createServer(requestCallback);
-var io = socketio.listen(app);
+// From 'https://github.com/mmukhin/psitsmike_example_1'
+var app = require('express').createServer();
+var io = require('socket.io').listen(app);
-app.listen(process.env.PORT || 80);
+app.listen(process.env.PORT || 8080);
-function requestCallback(req, res) {
- fs.readFile(__dirname + '/index.html', function (err, data) {
- if (err) {
- res.writeHead(404);
- return res.end('Error loading index.html');
- }
+app.get('/', function (req, res) {
+ res.sendfile(__dirname + '/index.html');
+});
- res.writeHead(200);
- res.end(data);
- });
-}
+var usernames = {};
io.sockets.on('connection', function (socket) {
- socket.emit('news', { hello: 'world' });
- socket.on('my other event', function (data) {
- console.log(data);
- });
+
+ socket.on('sendchat', function (data) {
+ io.sockets.emit('updatechat', socket.username, data);
+ });
+
+ socket.on('adduser', function(username){
+ socket.username = username;
+ usernames[username] = username;
+ socket.emit('updatechat', 'SERVER', 'you have connected');
+ socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
+ io.sockets.emit('updateusers', usernames);
+ });
+
+ socket.on('disconnect', function(){
+ delete usernames[socket.username];
+ io.sockets.emit('updateusers', usernames);
+ socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
+ });
});
```
+You'll notice there's a lote of new things in the example above. The first of which is the use
+of the "[express](http://expressjs.com/)" module. We aren't going to go into the
+details of express. While it does much more than just this, for now you can think of
+express as a module that simplifies request handling. It's what allows us to handle requests
+to '/' with a simple `app.get('/', ...`, it's also what allows us to send the user a file
+with one line (`res.sendfile(__dirname + '/index.html');`).
+
+The next thing that should stand out to you is the
+ `var io = require('socket.io').listen(app);` code near the top. This line is how socket.io
+piggybacks onto the existing HTTP server instance, as we mentioned earlier.
+
The code here should look familiar except in a couple spots: `var io =
socketio.listen(app);` and the `io.sockets.on` code at the bottom. The
`socketio.listen(app)` is how socket.io piggybacks onto your existing HTTP server
instance, as we mentioned earlier.
-By and large the syntax is very much like natural laguage. Socket.io listens for
-incoming connections on our HTTP server with a specific URL request. Only then
-will it call the callback function with the `socket` parameter supplied. This
-`socket` parameter is an object with everything we need to know about the
+By and large the syntax for socket.io is very much like natural language.
+Socket.io listens for incoming connections on our HTTP server with a specific URL request.
+Only then will it call the callback function with the `socket` parameter supplied.
+This `socket` parameter is an object with everything we need to know about the
connecting client.
From there we can send and receive messages to/from the client. `socket.emit`
sends a message (the 2nd parameter) on the namespace (1st parameter). In this
-case the namespace is 'news'. This means the client must be listening for
-messages on the 'news' namespace to receive the message. Let's see what this
-looks like on the client side:
+case the namespaces are 'updatechat' and 'updateusers'.
+This means the client must be listening for messages on one of those namespaces to
+ receive a message. Let's see what this looks like on the client side:
```javascript
var socket = io.connect();
-socket.on('news', function (data) {
- console.log(data);
- socket.emit('my other event', { my: 'data' });
-});
-```
-
-First a connection is initiated. When the socket receives a message on the 'news'
-namespace, it gets passed the `data` parameter.
-
-Let's say we want to create a simple chat application; every time we receive
-a message, we send the message to all clients. To achieve this, we'll create a
-'chat' namespace and restrict messages to just that namespace.
-```javascript
-var http = require('http');
-var socketio = require('socket.io');
-var fs = require('fs');
-
-var app = http.createServer(requestCallback);
-var io = socketio.listen(app);
-
-app.listen(process.env.PORT || 80);
-
-function requestCallback(req, res) {
- fs.readFile(__dirname + '/index.html', function (err, data) {
- if (err) {
- res.writeHead(404);
- return res.end('Error loading index.html');
- }
-
- res.writeHead(200);
- res.end(data);
- });
-}
-
-var chat = io.of('/chat').on('connection', function (socket) {
- socket.emit('a message', {
- to: 'the connecting user'
- });
- chat.emit('a message', {
- to: 'everyone'
- });
+socket.on('updatechat', function (username, data) {
+ $('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
});
```
-The client connects to the 'chat' namespace like so:
-
-```javascript
-var chat = io.connect('/chat');
-
-chat.on('connect', function () {
- chat.emit('hi!');
-});
-
-chat.on('a message', function(data) {
- console.log(data);
-});
-```
+First a connection is initiated. When the socket receives a message on the 'updatechat'
+namespace, it gets passed the `data` parameter. When this client receives an 'updatechat'
+message, it will use jQuery to append that message into the '#conversation' DIV.
-With this foundation you can start dreaming up ways to dispatch server-side
+Hopefully, with this foundation you can start dreaming up ways to dispatch server-side
events to your clients: a new chat message, a new database entry, a weather
advisory, new joystick movement.
View
61 sessions/hour2/04_socket-io-a-primer/server.js 100644 → 100755
@@ -1,27 +1,46 @@
-var http = require('http');
-var socketio = require('socket.io');
-var fs = require('fs');
+// From 'https://github.com/mmukhin/psitsmike_example_1'
+var app = require('express').createServer();
+var io = require('socket.io').listen(app);
-var app = http.createServer(requestCallback);
-var io = socketio.listen(app);
+app.listen(process.env.PORT || 8080);
-app.listen(process.env.PORT || 80);
+// routing
+app.get('/', function (req, res) {
+ res.sendfile(__dirname + '/index.html');
+});
-function requestCallback(req, res) {
- fs.readFile(__dirname + '/index.html', function (err, data) {
- if (err) {
- res.writeHead(404);
- return res.end('Error loading index');
- }
-
- res.writeHead(200);
- res.end(data);
- });
-}
+// usernames which are currently connected to the chat
+var usernames = {};
io.sockets.on('connection', function (socket) {
- socket.emit('news', { hello: 'world' });
- socket.on('my other event', function (data) {
- console.log(data);
- });
+
+ // when the client emits 'sendchat', this listens and executes
+ socket.on('sendchat', function (data) {
+ // we tell the client to execute 'updatechat' with 2 parameters
+ io.sockets.emit('updatechat', socket.username, data);
+ });
+
+ // when the client emits 'adduser', this listens and executes
+ socket.on('adduser', function(username){
+ // we store the username in the socket session for this client
+ socket.username = username;
+ // add the client's username to the global list
+ usernames[username] = username;
+ // echo to client they've connected
+ socket.emit('updatechat', 'SERVER', 'you have connected');
+ // echo globally (all clients) that a person has connected
+ socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
+ // update the list of users in chat, client-side
+ io.sockets.emit('updateusers', usernames);
+ });
+
+ // when the user disconnects.. perform this
+ socket.on('disconnect', function(){
+ // remove the username from global usernames list
+ delete usernames[socket.username];
+ // update list of users in chat, client-side
+ io.sockets.emit('updateusers', usernames);
+ // echo globally that this client has left
+ socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
+ });
});
Please sign in to comment.
Something went wrong with that request. Please try again.