Building a chat application with Node.js libraries

Schedule

  1. warm-up
  2. Express library
  3. Our stack: Node.js, Express, Socket.io
  4. “CoolChat” - Node.js with Express and Socket.io
  5. Node libraries
  6. Clock assignment - 1-on-1s and studio time

Game and Performance Talk with Kristin McWharter

4:45pm

Zoom

Kristin McWharter uses performance and play to interrogate the relationship between competition and intimacy. Her work conjoins viewers within immersive sculptural installations and viewer-inclusive performances that critically fuse folk games within virtual and augmented worlds. Her software installations and performative objects incorporate experimental technologies and playful interaction to produce performances that speculate upon alternative forms of social behavior. Inspired by 20th century sports narrative, collective decision making, and technology as a contemporary spiritual authority, her work blurs the boundaries of intimacy and hype culture to challenge viewer’s relationships to affection and competitive drive within our current social context. Her work has been exhibited at The Hammer Museum, Walt Disney Concert Hall, Bangkok Arts and Cultural Center, Ars Electronica, Museo Altillo Beni, and FILE Festival. McWharter received her MFA from UCLA in Design Media Arts and is currently an Assistant Professor in Art & Technology Studies at SAIC where she teaches courses: experimental media, New Realities: Simulations of Future Worlds and virtual reality.

More about Express

What does Express do for us? Why are we using it?

Let’s visit the website for Express.

It explains that Express is a fast, unopionated minimalist web framework. Fast is obvious. Unopinionated is coder-speak for: “you can write code any which way you please. There isn’t a single way you have to write it if you use our library with it.” Okay, but what is a web framework?

Express provides a simple way (a mini “language”) to serve pages. It is like a switchboard operator that receives a call (“Hello, I’d like to speak to lee in Henley-4562”). What are we routing? When a user requests a particular webpage, that gets routed via our code, and specific content (“a view”) is served.

How does this work? Express looks for the route specified in the URL bar.

MyWebsite.com/theRouteIamRequesting

the Route looks like a sub-folder, but it’s actually a bit of information that is communicated. Express takes this info, and then figures out what to display.

Intro to Socket.io

–resources from Todd Anderson

For this tutorial, our starter code and learning resource can be found here. Our front door is here.

Socket.io is a javascript library that runs in both the browser and server to allow realtime communication between the two. This allows for collaborative web experiences where many people can interact on the same page, all without using a cumbersome database or even much backend code.

Socket.io does this by having both a client-side and a server-side library which communicate with each other through named events that pass between the two (similar to the way keyboard and mouse events are handled).

Below is a rough guide to how socket.io works on the client side and on the server side, and how the two communicate.

Client Side

On the client side, the socket.io client library needs to be included in the HTML:

<script src= 'https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js'></script>

And the following line needs to be included at the top of your client.js file:

var socket = io()

The client can then send messages to the server in the following form

//the function takes a string and then an object full of data (any size)
socket.emit('nameOfEvent', {data: "data you are sending to the server"})

And the client can listen for messages from the server like so:

socket.on('nameOfServerEvent', function(data){
  //the code you want to use on the data sent back from the server
}

Server Side

Just about all of your socket.io programs are going to want the following boilerplate in the server.js file.

starter code

var socket = require('socket.io');
var io = socket(server);

io.sockets.on('connection', newConnection);

//This function will be called whenever a new web browser visits the page. It runs as soon as a connection is set up with the server.

function newConnection(socket){
    console.log('new connection: ' + socket.id)
    //we put all the rest of our code inside that connection, because we only want it to run once we're connected
  //this section will have one or more event listeners that line up with various things that can happen on the client side (like sending a message in a chat app)
    socket.on('myEvent', myEventHandler);
    function myEventHandler(data){
    //what you do in response to the event goes here
    //often you'll want one of the four 'emit' events listed below
    socket.broadcast.emit('myServerEvent', data);
        
    }
}

Server Side Cheat Sheet

  socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

  // sending to all clients except sender
  socket.broadcast.emit('broadcast', 'hello friends!');

  // sending to all clients in 'game' room except sender
  socket.to('game').emit('nice game', "let's play a game");

  // sending to all clients in 'game1' and/or in 'game2' room, except sender
  socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

  // sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

  // sending to individual socketid (private message)
  io.to(socketId).emit('hey', 'I just met you');

Message Passing Example: Chat Room

A user logs into a chat room using socket.io. Once the page loads a connection is established, giving the user a unique id and trigger the newConnection function through the following part of the server code


io.sockets.on('connection', newConnection);

function newConnection(socket){
 //...
}

The user enters their username on the client, and then types and sends a message into the chatroom. The following client-side code sends the message:

socket.emit('newMsg', {username:username, msg:msg});

This is then handled by the appropriate handler on the server (with the matching name):

function newConnection(socket){
   socket.on('newMsg', function(data){
     //the same data from the client is sent to all other clients
     socket.broadcast.emit('newMsgFromServer', data)
   }
}

The server receives the message and then sends it out to all other connected clients. This message from the server is then handled by the following code on the client:


socket.on('newMsgFromServer', function(data){
    addMsg(data.username, data.msg)
})

//This function uses jQuery to add the message to the HTML
function addMsg(user, msg){
    $('#messages').append("<p><strong>"+user+": </strong>"+msg+"</p>")
}

Chatroom with Node.js, Express and Socket.io

Parts

Node.js to manage the server.

Express to handle the routes.

Socket.io for sending messages.

CoolChat starter code

Adding NPM packages on Glitch.com

When you click package.json you have the ability to install additional npm packages. By clicking Add Package, you may access any package from the NPM registry.

add a npm package on glitch

Homework: finish custom clock

This is a project to use the Date() API in the browser to flex your muscle with HTML, CSS and JS to build a web application. You can choose what you want to make with this framework, but make it unique. Show us your creative take.

Examples:

This project is due Apr 3

This project will be evaluated by: