Lecture 17
Lecture 17
Important Note
• The slides are accompanied by code snippets that were covered
during the class.
• Required Node.JS packages are listed in the provided code files.
2
Socket Communication
• Sockets provide a bi-directional communication channel between a
client and a server for real time data exchange.
• A client can push messages to a server and a server can also push
messages to a client any time.
• Sockets are typically used for applications such as chat apps,
gaming, or real-time collaboration tools, live notifications (sports
updates etc.).
3
Socket Communication
• A socket represents an endpoint for communication between two
machines over a network.
• Typically, there is a client (which initiates the communication) and
a server (which listens for incoming connections).
• The server listens on a specific port for incoming connections
from clients.
• Once a client establishes a connection to the server, they can
communicate and exchange data.
4
Socket.IO
• Socket.IO is a JavaScript library that enables real-time,
bidirectional communication between web clients (such as
browsers) and servers.
• Socket.IO uses WebSockets (a protocol for real-time
communication) and provides additional features that make it
easier to implement real-time applications like chat apps, live
updates, multiplayer games etc.
5
Socket.IO: Application Components
• A Socket.IO server integrates with (or mounts on) the Node.JS
HTTP Server (using the socket.io package)
• We create a web server in Node.JS and integrates Socket.IO server with it.
• A client that loads on the browser side (using the socket.io-client
package)
6
Socket.IO: Server
express() is an Express library function
which returns an Express application
object. This object provides various
methods to handle HTTP requests,
routing, middleware and more.
7
Socket.IO: Server
Creates a new HTTP server
instance that can handle
HTTP requests. This server
can respond to HTTP
requests made by clients
(such as web browsers, or
any other HTTP client)
8
Socket.IO: Server initialize and configure the
Socket.IO server with an HTTP
server.
The Server class is responsible
for managing WebSocket
connections and enabling real-
time communication between
the server and clients.
Passing an existing HTTP server
(httpServer) to the Server
constructor tells Socket.IO to
manage WebSocket
connections through HTTP
Server. The Server class adds
WebSocket functionality to the
HTTP server
9
Socket.IO: Server
10
Socket.IO: Server
11
Socket.IO: Server
12
Socket.IO: Server
13
Socket.IO: Server
14
Socket.IO: Server
15
Socket.IO: Client
A socket-client object is
created for communication
with a web socket server
running at the provided URL
16
Socket.IO: Client
A connection is established
with a web socket server.
17
Socket.IO: Client
18
Socket.IO: Client
19
Socket.IO: Client
20
References
• https://socket.io/
• Learning TypeScript by Josh Goldberg
• Node.js in Action by Alex Young etc.
21