From b41d6caedc092bd26326a6b77b6e79d14af9bdb5 Mon Sep 17 00:00:00 2001 From: Vatsal Mehta Date: Thu, 3 Oct 2024 09:37:51 -0400 Subject: [PATCH 1/5] Initial Socket.IO tutorial outline --- tutorials/week5-socketio.md | 50 +++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 tutorials/week5-socketio.md diff --git a/tutorials/week5-socketio.md b/tutorials/week5-socketio.md new file mode 100644 index 0000000..e4273ce --- /dev/null +++ b/tutorials/week5-socketio.md @@ -0,0 +1,50 @@ +--- +layout: page +title: Socket.IO Tutorial +permalink: /tutorials/week5-socketio-basics +parent: Tutorials +nav_order: 7 +--- + +This tutorial covers the basic concepts of Socket.IO. By the end of the tutorial, you'll have an introduction to the concept of web sockets for client-server communication, understand in what situations they are useful, and learn how to emit and listen for events for real-time updates. + +Contents: + +- [What is Socket.IO](#what-is-socketio) +- [Socket.IO vs. REST APIs](#socketio-vs-rest-apis) +- [Set Up a New Project](#set-up-a-new-project) +- [Emitting & Receiving Socket Events](#emitting-and-receiving-socket-events) +- [Useful Resources](#useful-resources) + +# What is Socket.IO? + +Examples (notes): + +- Chat room +- Multiplayer games +- Covey Town-like app + +# Socket.IO vs. REST APIs + +Notes to include here: + +- Persistent connection vs temporary connection +- Subscriber vs pulling design pattern (module 5) +- Advantages vs disadvantages + +# Set Up a New Project + +# Emitting and Receiving Socket Events + +Notes to include here: + +- Creating a socket object on client/server +- Setting up a connection +- Emitting an update + object with the update +- Subscribing a listener to an update + handler function for emitted object + +# Useful Resources + +- [Socket.IO Introduction (Documentation)](https://socket.io/docs/v4/tutorial/introduction) +- [Socket.IO Chat App Tutorial (Documentation)](https://socket.io/get-started/chat) +- [Learn Socket.io In 30 Minutes - Web Dev Simplified](https://www.youtube.com/watch?v=ZKEqqIO7n-k) From 9165e380d6974c752f48108f3cfce4804c341d05 Mon Sep 17 00:00:00 2001 From: Vatsal Mehta Date: Thu, 3 Oct 2024 15:39:12 -0400 Subject: [PATCH 2/5] Added Socket.IO intro --- tutorials/week5-socketio.md | 45 ++++++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 11 deletions(-) diff --git a/tutorials/week5-socketio.md b/tutorials/week5-socketio.md index e4273ce..cbb1a41 100644 --- a/tutorials/week5-socketio.md +++ b/tutorials/week5-socketio.md @@ -6,31 +6,54 @@ parent: Tutorials nav_order: 7 --- -This tutorial covers the basic concepts of Socket.IO. By the end of the tutorial, you'll have an introduction to the concept of web sockets for client-server communication, understand in what situations they are useful, and learn how to emit and listen for events for real-time updates. +This tutorial covers the basic concepts of Socket.IO. By the end of the tutorial, you'll have an introduction to the concept of sockets for client-server communication, understand in what situations they are useful, and learn how to emit and listen for events for real-time updates. Contents: - [What is Socket.IO](#what-is-socketio) -- [Socket.IO vs. REST APIs](#socketio-vs-rest-apis) + - [How Does It Work?](#how-does-it-work) + - [Socket.IO vs. REST APIs](#socketio-vs-rest-apis) + - [Example Uses](#example-uses) - [Set Up a New Project](#set-up-a-new-project) - [Emitting & Receiving Socket Events](#emitting-and-receiving-socket-events) - [Useful Resources](#useful-resources) # What is Socket.IO? -Examples (notes): +Socket.IO is a library that enables real-time, bidirectional, and persistent communication between client(s) and server(s). Bi-directional means that both the client and the server can send or receive messages. These features make it particularly useful for applications requiring continuous data sharing, such as live dashboards and chat apps. -- Chat room -- Multiplayer games -- Covey Town-like app +## How Does It Work? -# Socket.IO vs. REST APIs +Socket.IO follows the ["observer pattern" or "listener pattern"](https://neu-se.github.io/CS4530-Fall-2024/modules/5-interaction-level-design-patterns) discussed in class. In this context: -Notes to include here: +- **Publisher** - A publisher can be identified where `.emit` is used. This _emits_ (sends) out data to the specified channel, making it available to any _subscriber_ to the channel. +- **Subscriber** - A subscriber can be identified where `.on` is used. This listens for updates emitted by a _publisher_ to the specified channel and executes the handler function (if applicable). + +The code implementations below explore this in more depth. + +Internally, Socket.IO establishes WebSocket connections where possible to send data. You can read more about the protocols in the [documentation](https://socket.io/docs/v4/how-it-works/). + +## Socket.IO vs. REST APIs + +A brief comparison between communication with Socket.IO and REST APIs: + +| Feature | Socket.IO | REST API | +| ------------------ | --------------------------------------- | ------------------------------------- | +| **Design Pattern** | Bidirectional, Publisher-Subscriber | Server -> Client Response, Data-pull | +| **Connection** | Persistent (WebSocket or fallback) | Temporary (HTTP request) | +| **Use Cases** | Real-time, low-latency data sharing | CRUD operations, static data | +| **Data Flow** | Server and client can send data anytime | Client-initiated requests (on-demand) | +| **Statefulness** | Stateful | Stateless | + +## Example Uses: + +Socket.IO is great for any use case where real-time updates are essential, or when the client and server need continuous communication. A few examples are: + +1. Chat Room - This is a simple use case outlined in the documentation (linked below). Users need to send and receive messages in real-time (instantly). With Socket.IO, the user can emit a message to the server, which then broadcasts it with the other connected users. If you were to use a REST API here, there would a lot of overhead and latency in sending/receiving messages due to the constant need of sending requests to the API. + +2. Multiplayer Games - Real-time game state sharing with low latency is essential for smooth mutliplayer gameplay. By emitting socket events with the updated game state, you can make sure that all of the connected player clients have the same, synchronized copy of the game state to display. -- Persistent connection vs temporary connection -- Subscriber vs pulling design pattern (module 5) -- Advantages vs disadvantages +3. Collaborative Tools - For applications like collaborative text editors or whiteboards, sockets can help keep the state synchronized across the clients. When a user makes a change, the change will be emitted to the server, which may internall update the "source of truth" for the application. Then, the updated state would be emitted to all other connected clients, so that everyone sees the edits in real-time. # Set Up a New Project From f94f015718b5b23c0929b86f452ab36b6a9fa9db Mon Sep 17 00:00:00 2001 From: Sai Vihar Reddy Gunamgari <44550857+ViharReddy@users.noreply.github.com> Date: Fri, 4 Oct 2024 17:56:00 -0400 Subject: [PATCH 3/5] Update week5-socketio.md --- tutorials/week5-socketio.md | 212 +++++++++++++++++++++++++++++++++++- 1 file changed, 207 insertions(+), 5 deletions(-) diff --git a/tutorials/week5-socketio.md b/tutorials/week5-socketio.md index cbb1a41..3e8498a 100644 --- a/tutorials/week5-socketio.md +++ b/tutorials/week5-socketio.md @@ -57,14 +57,216 @@ Socket.IO is great for any use case where real-time updates are essential, or wh # Set Up a New Project +To get started with Socket.IO, you'll need to set up a Node.js project. Follow these steps: +1. Initialize a Node.js Project\ + First, create a new directory for your project and navigate into it: + ``` + mkdir socketio-tutorial + cd socketio-tutorial + ``` + + Now initialize a new Node.js project by running the following command: + ``` + npm init -y + ``` + This will generate a package.json file with the default configuration. + +2. Install the Necessary Packages\ + To use Socket.IO, you'll need to install both `express` (for setting up a basic HTTP server) and `socket.io` itself. + Run the following command to install both: + ``` + npm install express socket.io + ``` + +3. Set Up a Basic Server\ + Now, lets create the server. Inside your project directory, create a file called `server.js`: + ``` + touch server.js + ``` + Open `server.js` and write the following code to create a basic HTTP server with Socket.IO: + ``` + const express = require('express'); + const http = require('http'); + const { Server } = require('socket.io'); + + const app = express(); + const server = http.createServer(app); + const io = new Server(server); + + // Serve a simple HTML page (or use this for serving static files) + app.get('/', (req, res) => { + res.sendFile(__dirname + '/index.html'); + }); + + // Set up a connection handler + io.on('connection', (socket) => { + console.log('A user connected'); + + // Clean up when the client disconnects + socket.on('disconnect', () => { + console.log('A user disconnected'); + }); + }); + + const PORT = 3000; + server.listen(PORT, () => { + console.log(`Server is running on http://localhost:${PORT}`); + }); + ``` + This will setup a basic HTTP server that uses Socket.IO to establish connections. Now, let's create a simple client. + +4. Create a Client-Side HTML File\ + In your project directory, create a file called `index.html`: + ``` + touch index.html + ``` + Now, open `index.html` and add the following code: + ``` + + + + + + Socket.IO Tutorial + + + +

Hello Socket.IO!

+ + + + ``` + This HTML file sets up a basic client-side script that connects to the server using Socket.IO. + +5. Run Your Project\ + To start the server, run the following command: + ``` + node server.js + ``` + Then, open a browser and go to `http://localhost:3000`. You should see "Hello Socket.IO!" on the page, and in the browser's developer console, you'll see a essage confirming the connection. + + # Emitting and Receiving Socket Events +Now that you've set up a basic project, let's dive into how you can emit and receive Socket.IO events to communicate between the client and server. + +1. Creating a Socket Object on CLient and Server\ +Client-Side: +When the browser loads the HTML page, it creates a `socket` object that connects to the server. +We've already initialized the socket object in the script section of `index.html`: +``` +const socket = io(); // Automatically connects to the server +``` +Server-Side: +On the server, Socket.IO will create a `socket` object for each client that connects. You can listen for connections with the `io.on('connection')` event: +``` +io.on('connection', (socket) => { + console.log('A user connected'); +}); +``` + +2. Setting Up a Connection\ +Once the socket object is created, both the client and server can start emitting and receiving events. +Example: Handling Connections and Disconnections +We can already see basic connection handling: +``` +// Server-side +io.on('connection', (socket) => { + console.log('A user connected'); + + socket.on('disconnect', () => { + console.log('A user disconnected'); + }); +}); +``` +On the client side, you can also listen for the `connect` and `disconnect` events: +``` +// Client-side +socket.on('connect', () => { + console.log('Connected to the server'); +}); + +socket.on('disconnect', () => { + console.log('Disconnected from the server'); +}); +``` + +3. Emitting an Update + Object with the Update\ +To send data from the client to the server or vice versa, you use the `.emit()` method. +Example: Emitting a Custom Event +Let's say we want to send a chat message from the client to the server. You can emit a custom event like this: +``` +// Client-side +socket.emit('chat message', { user: 'John', message: 'Hello, World!' }); +``` +On the server side, you can listen for this event and handle the received data: +``` +// Server-side +socket.on('chat message', (data) => { + console.log(`${data.user}: ${data.message}`); +}); +``` +You can also send data back to all connected client: +``` +// Server-side +io.emit('chat message', { user: 'Server', message: 'Welcome to the chat!' }); +``` + +4. Subscribing a Listener to an Update + Handler Function for Emitted Object\ +On the client side, you need to subscribe to the event to receive the emitted messages: +``` +// Client-side +socket.on('chat message', (data) => { + console.log(`${data.user}: ${data.message}`); +}); +``` +This will allow the client to receive and handle chat messages sent from the server (or other clients). + +Putting It All Together +Here's an example of a simple chat app: +Server-Side (`server.js`)" +``` +io.on('connection', (socket) => { + console.log('A user connected'); + + socket.on('chat message', (data) => { + console.log(`${data.user}: ${data.message}`); + // Broadcast the message to all clients + io.emit('chat message', data); + }); + + socket.on('disconnect', () => { + console.log('A user disconnected'); + }); +}); +``` +Client-Side (`index.html`): +``` + +``` +This example sets up a basic chat app where users can send and receive messages in real time. -- Creating a socket object on client/server -- Setting up a connection -- Emitting an update + object with the update -- Subscribing a listener to an update + handler function for emitted object # Useful Resources From 8198ff48a35ca5cd168ad31282cf33501952f220 Mon Sep 17 00:00:00 2001 From: Sai Vihar Reddy Gunamgari <44550857+ViharReddy@users.noreply.github.com> Date: Fri, 4 Oct 2024 20:27:25 -0400 Subject: [PATCH 4/5] Update week5-socketio.md used ts instead of js --- tutorials/week5-socketio.md | 131 +++++++++++++++++++----------------- 1 file changed, 69 insertions(+), 62 deletions(-) diff --git a/tutorials/week5-socketio.md b/tutorials/week5-socketio.md index 3e8498a..5dcffd3 100644 --- a/tutorials/week5-socketio.md +++ b/tutorials/week5-socketio.md @@ -58,62 +58,69 @@ Socket.IO is great for any use case where real-time updates are essential, or wh # Set Up a New Project To get started with Socket.IO, you'll need to set up a Node.js project. Follow these steps: + 1. Initialize a Node.js Project\ - First, create a new directory for your project and navigate into it: - ``` - mkdir socketio-tutorial - cd socketio-tutorial - ``` +First, create a new directory for your project and navigate into it: +``` +mkdir socketio-tutorial +cd socketio-tutorial +``` - Now initialize a new Node.js project by running the following command: - ``` - npm init -y - ``` - This will generate a package.json file with the default configuration. +Now initialize a new Node.js project by running the following command: +``` +npm init -y +``` +This will generate a package.json file with the default configuration. 2. Install the Necessary Packages\ - To use Socket.IO, you'll need to install both `express` (for setting up a basic HTTP server) and `socket.io` itself. - Run the following command to install both: - ``` - npm install express socket.io - ``` +To use Socket.IO, you'll need to install both `express` (for setting up a basic HTTP server) and `socket.io` itself. Also, you need to install `typescript`, the type definitions for both `express` and `socket.io` and some utilities to support TypeScript development. +Run the following command to install everything that is needed for this project: +``` +npm install --save-dev typescript express @types/express socket.io @types/socket.io ts-node +``` +To configure TypeScript, you need to add a `tsconfig.json`. You can create this file manually or run: +``` +npx tsc --init +``` +This will generate a basic `tsconfig.json` with the default configuration. 3. Set Up a Basic Server\ - Now, lets create the server. Inside your project directory, create a file called `server.js`: - ``` - touch server.js - ``` - Open `server.js` and write the following code to create a basic HTTP server with Socket.IO: - ``` - const express = require('express'); - const http = require('http'); - const { Server } = require('socket.io'); - - const app = express(); - const server = http.createServer(app); - const io = new Server(server); - - // Serve a simple HTML page (or use this for serving static files) - app.get('/', (req, res) => { - res.sendFile(__dirname + '/index.html'); - }); - - // Set up a connection handler - io.on('connection', (socket) => { - console.log('A user connected'); - - // Clean up when the client disconnects - socket.on('disconnect', () => { - console.log('A user disconnected'); - }); - }); - - const PORT = 3000; - server.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); +Now, lets create the server. Inside your project directory, create a file called `server.ts`: +``` +touch server.ts +``` +Open `server.ts` and write the following code to create a basic HTTP server with Socket.IO: +``` +import express, { Request, Response } from "express"; +import http from "http"; +import { Server, Socket } from "socket.io"; +import path from "path"; + +const app = express(); +const server = http.createServer(app); +const io = new Server(server); + +// Serve a simple HTML page (or use this for serving static files) +app.get("/", (req: Request, res: Response) => { + res.sendFile(path.join(__dirname, "index.html")); +}); + +// Set up a connection handler +io.on("connection", (socket: Socket) => { + console.log("A user connected"); + + // Clean up when the client disconnects + socket.on("disconnect", () => { + console.log("A user disconnected"); }); - ``` - This will setup a basic HTTP server that uses Socket.IO to establish connections. Now, let's create a simple client. +}); + +const PORT = 3000; +server.listen(PORT, () => { + console.log(`Server is running on http://localhost:${PORT}`); +}); +``` +This will setup a basic HTTP server that uses Socket.IO to establish connections. Now, let's create a simple client. 4. Create a Client-Side HTML File\ In your project directory, create a file called `index.html`: @@ -151,17 +158,17 @@ To get started with Socket.IO, you'll need to set up a Node.js project. Follow t This HTML file sets up a basic client-side script that connects to the server using Socket.IO. 5. Run Your Project\ - To start the server, run the following command: - ``` - node server.js - ``` - Then, open a browser and go to `http://localhost:3000`. You should see "Hello Socket.IO!" on the page, and in the browser's developer console, you'll see a essage confirming the connection. +To start the server, run the following command: +``` +ts-node server.ts +``` +Then, open a browser and go to `http://localhost:3000`. You should see "Hello Socket.IO!" on the page, and in the browser's developer console, you'll see a essage confirming the connection. # Emitting and Receiving Socket Events Now that you've set up a basic project, let's dive into how you can emit and receive Socket.IO events to communicate between the client and server. -1. Creating a Socket Object on CLient and Server\ +1. Creating a Socket Object on Client and Server\ Client-Side: When the browser loads the HTML page, it creates a `socket` object that connects to the server. We've already initialized the socket object in the script section of `index.html`: @@ -171,7 +178,7 @@ const socket = io(); // Automatically connects to the server Server-Side: On the server, Socket.IO will create a `socket` object for each client that connects. You can listen for connections with the `io.on('connection')` event: ``` -io.on('connection', (socket) => { +io.on('connection', (socket: Socket) => { console.log('A user connected'); }); ``` @@ -182,7 +189,7 @@ Example: Handling Connections and Disconnections We can already see basic connection handling: ``` // Server-side -io.on('connection', (socket) => { +io.on('connection', (socket: Socket) => { console.log('A user connected'); socket.on('disconnect', () => { @@ -213,7 +220,7 @@ socket.emit('chat message', { user: 'John', message: 'Hello, World!' }); On the server side, you can listen for this event and handle the received data: ``` // Server-side -socket.on('chat message', (data) => { +socket.on('chat message', (data: { user: string; message: string }) => { console.log(`${data.user}: ${data.message}`); }); ``` @@ -227,7 +234,7 @@ io.emit('chat message', { user: 'Server', message: 'Welcome to the chat!' }); On the client side, you need to subscribe to the event to receive the emitted messages: ``` // Client-side -socket.on('chat message', (data) => { +socket.on('chat message', (data: { user: string; message: string }) => { console.log(`${data.user}: ${data.message}`); }); ``` @@ -235,12 +242,12 @@ This will allow the client to receive and handle chat messages sent from the ser Putting It All Together Here's an example of a simple chat app: -Server-Side (`server.js`)" +Server-Side (`server.ts`)" ``` io.on('connection', (socket) => { console.log('A user connected'); - socket.on('chat message', (data) => { + socket.on('chat message', (data: { user: string; message: string }) => { console.log(`${data.user}: ${data.message}`); // Broadcast the message to all clients io.emit('chat message', data); @@ -257,7 +264,7 @@ Client-Side (`index.html`): const socket = io(); // Listen for chat messages - socket.on('chat message', (data) => { + socket.on('chat message', (data: { user: string; message: string }) => { console.log(`${data.user}: ${data.message}`); }); From 55b126f287ad9420ef71180047f9385d46274f49 Mon Sep 17 00:00:00 2001 From: Vatsal Mehta Date: Fri, 4 Oct 2024 21:45:13 -0400 Subject: [PATCH 5/5] updated formatting and fixed typos --- tutorials/week5-socketio.md | 425 ++++++++++++++++++++---------------- 1 file changed, 239 insertions(+), 186 deletions(-) diff --git a/tutorials/week5-socketio.md b/tutorials/week5-socketio.md index 5dcffd3..fdb4d7b 100644 --- a/tutorials/week5-socketio.md +++ b/tutorials/week5-socketio.md @@ -14,8 +14,10 @@ Contents: - [How Does It Work?](#how-does-it-work) - [Socket.IO vs. REST APIs](#socketio-vs-rest-apis) - [Example Uses](#example-uses) -- [Set Up a New Project](#set-up-a-new-project) -- [Emitting & Receiving Socket Events](#emitting-and-receiving-socket-events) +- [Using Socket.IO](#using-socketio) + - [Set Up a New Project](#set-up-a-new-project) + - [Emitting & Receiving Socket Events](#emitting-and-receiving-socket-events) + - [Putting It All Together](#putting-it-all-together) - [Useful Resources](#useful-resources) # What is Socket.IO? @@ -27,7 +29,7 @@ Socket.IO is a library that enables real-time, bidirectional, and persistent com Socket.IO follows the ["observer pattern" or "listener pattern"](https://neu-se.github.io/CS4530-Fall-2024/modules/5-interaction-level-design-patterns) discussed in class. In this context: - **Publisher** - A publisher can be identified where `.emit` is used. This _emits_ (sends) out data to the specified channel, making it available to any _subscriber_ to the channel. -- **Subscriber** - A subscriber can be identified where `.on` is used. This listens for updates emitted by a _publisher_ to the specified channel and executes the handler function (if applicable). +- **Subscriber** - A subscriber can be identified where `.on` is used. This listens for updates emitted by a _publisher_ to the specified channel and executes a handler function (if applicable). The code implementations below explore this in more depth. @@ -49,231 +51,282 @@ A brief comparison between communication with Socket.IO and REST APIs: Socket.IO is great for any use case where real-time updates are essential, or when the client and server need continuous communication. A few examples are: -1. Chat Room - This is a simple use case outlined in the documentation (linked below). Users need to send and receive messages in real-time (instantly). With Socket.IO, the user can emit a message to the server, which then broadcasts it with the other connected users. If you were to use a REST API here, there would a lot of overhead and latency in sending/receiving messages due to the constant need of sending requests to the API. +1. Chat Room - This is a simple use case outlined in the documentation (linked below). Users need to send and receive messages in real-time (instantly). With Socket.IO, the user can emit a message to the server, which then broadcasts it with the other connected users. If you were to use a REST API here, there would a lot of overhead and latency in sending/receiving messages from the need of constant requests to the API. -2. Multiplayer Games - Real-time game state sharing with low latency is essential for smooth mutliplayer gameplay. By emitting socket events with the updated game state, you can make sure that all of the connected player clients have the same, synchronized copy of the game state to display. +2. Multiplayer Games - Real-time game state sharing with low latency is essential for smooth multiplayer gameplay. By emitting socket events with the updated game state, you can make sure that all of the connected player clients have the same synchronized copy of the game state to display. -3. Collaborative Tools - For applications like collaborative text editors or whiteboards, sockets can help keep the state synchronized across the clients. When a user makes a change, the change will be emitted to the server, which may internall update the "source of truth" for the application. Then, the updated state would be emitted to all other connected clients, so that everyone sees the edits in real-time. +3. Collaborative Tools - For applications like collaborative text editors or whiteboards, sockets can help keep the state synchronized across the clients. When a user makes a change, the change will be emitted to the server, which may internally update the "source of truth" for the application. Then, the updated state would be emitted to all other connected clients, so that everyone sees the edits in real-time. -# Set Up a New Project +# Using Socket.IO + +## Set Up a New Project To get started with Socket.IO, you'll need to set up a Node.js project. Follow these steps: -1. Initialize a Node.js Project\ -First, create a new directory for your project and navigate into it: -``` -mkdir socketio-tutorial -cd socketio-tutorial -``` +1. **Initialize a Node.js Project** -Now initialize a new Node.js project by running the following command: -``` -npm init -y -``` -This will generate a package.json file with the default configuration. + First, create a new directory for your project and navigate into it: -2. Install the Necessary Packages\ -To use Socket.IO, you'll need to install both `express` (for setting up a basic HTTP server) and `socket.io` itself. Also, you need to install `typescript`, the type definitions for both `express` and `socket.io` and some utilities to support TypeScript development. -Run the following command to install everything that is needed for this project: -``` -npm install --save-dev typescript express @types/express socket.io @types/socket.io ts-node -``` -To configure TypeScript, you need to add a `tsconfig.json`. You can create this file manually or run: -``` -npx tsc --init -``` -This will generate a basic `tsconfig.json` with the default configuration. + ``` + mkdir socketio-tutorial + cd socketio-tutorial + ``` -3. Set Up a Basic Server\ -Now, lets create the server. Inside your project directory, create a file called `server.ts`: -``` -touch server.ts -``` -Open `server.ts` and write the following code to create a basic HTTP server with Socket.IO: -``` -import express, { Request, Response } from "express"; -import http from "http"; -import { Server, Socket } from "socket.io"; -import path from "path"; - -const app = express(); -const server = http.createServer(app); -const io = new Server(server); - -// Serve a simple HTML page (or use this for serving static files) -app.get("/", (req: Request, res: Response) => { - res.sendFile(path.join(__dirname, "index.html")); -}); + Now initialize a new Node.js project by running the following command: -// Set up a connection handler -io.on("connection", (socket: Socket) => { - console.log("A user connected"); + ``` + npm init -y + ``` - // Clean up when the client disconnects - socket.on("disconnect", () => { - console.log("A user disconnected"); - }); -}); + This will generate a package.json file with the default configuration. -const PORT = 3000; -server.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`); -}); -``` -This will setup a basic HTTP server that uses Socket.IO to establish connections. Now, let's create a simple client. - -4. Create a Client-Side HTML File\ - In your project directory, create a file called `index.html`: - ``` - touch index.html - ``` - Now, open `index.html` and add the following code: - ``` - - - - - - Socket.IO Tutorial - - - -

Hello Socket.IO!

- - - - ``` - This HTML file sets up a basic client-side script that connects to the server using Socket.IO. - -5. Run Your Project\ -To start the server, run the following command: -``` -ts-node server.ts -``` -Then, open a browser and go to `http://localhost:3000`. You should see "Hello Socket.IO!" on the page, and in the browser's developer console, you'll see a essage confirming the connection. +2. **Install the Necessary Packages** + + To use Socket.IO, you'll need to install both `express` (for setting up a basic HTTP server) and `socket.io` itself. Also, you need to install `typescript`, the type definitions for both `express` and `socket.io` and some utilities to support TypeScript development. + + Run the following command to install everything that is needed for this project: + + ``` + npm install --save-dev typescript express @types/express socket.io @types/socket.io ts-node + ``` + + To configure TypeScript, you need to add a `tsconfig.json`. You can create this file manually or run: + + ``` + npx tsc --init + ``` + This will generate a basic `tsconfig.json` with the default configuration. + +3. **Set Up a Basic Server** + + Now, let's create the server. Inside your project directory, create a file called `server.ts`: + + ``` + touch server.ts + ``` + + Open `server.ts` and write the following code to create a basic HTTP server with Socket.IO: + + ```typescript + import express, { Request, Response } from "express"; + import http from "http"; + import { Server, Socket } from "socket.io"; + import path from "path"; + + const app = express(); + const server = http.createServer(app); + const io = new Server(server); + + // Serve a simple HTML page (or use this for serving static files) + app.get("/", (req: Request, res: Response) => { + res.sendFile(path.join(__dirname, "index.html")); + }); + + // Set up a connection handler + io.on("connection", (socket: Socket) => { + console.log("A user connected"); + + // Clean up when the client disconnects + socket.on("disconnect", () => { + console.log("A user disconnected"); + }); + }); + + const PORT = 3000; + server.listen(PORT, () => { + console.log(`Server is running on http://localhost:${PORT}`); + }); + ``` + + This will setup a basic HTTP server that uses Socket.IO to establish connections. Now, let's create a simple client. + +4. **Create a Client-Side HTML File** + + In your project directory, create a file called `index.html`: + + ``` + touch index.html + ``` + + Now, open `index.html` and add the following code: + + ```html + + + + + + Socket.IO Tutorial + + + +

Hello Socket.IO!

+ + + + ``` + + This HTML file sets up a basic client-side script that connects to the server using Socket.IO. + +5. **Run Your Project** + + To start the server, run the following command: + + ``` + ts-node server.ts + ``` + + Then, open a browser and go to `http://localhost:3000`. You should see "Hello Socket.IO!" on the page, and in the browser's developer console, you'll see a message confirming the connection. + +## Emitting and Receiving Socket Events -# Emitting and Receiving Socket Events Now that you've set up a basic project, let's dive into how you can emit and receive Socket.IO events to communicate between the client and server. -1. Creating a Socket Object on Client and Server\ -Client-Side: -When the browser loads the HTML page, it creates a `socket` object that connects to the server. -We've already initialized the socket object in the script section of `index.html`: -``` -const socket = io(); // Automatically connects to the server -``` -Server-Side: -On the server, Socket.IO will create a `socket` object for each client that connects. You can listen for connections with the `io.on('connection')` event: -``` -io.on('connection', (socket: Socket) => { - console.log('A user connected'); -}); -``` +1. **Creating a Socket Object on Client and Server** -2. Setting Up a Connection\ -Once the socket object is created, both the client and server can start emitting and receiving events. -Example: Handling Connections and Disconnections -We can already see basic connection handling: -``` -// Server-side -io.on('connection', (socket: Socket) => { - console.log('A user connected'); + Client-Side: + When the browser loads the HTML page, it creates a `socket` object that connects to the server. + We've already initialized the socket object in the script section of `index.html`: - socket.on('disconnect', () => { - console.log('A user disconnected'); - }); -}); -``` -On the client side, you can also listen for the `connect` and `disconnect` events: -``` -// Client-side -socket.on('connect', () => { - console.log('Connected to the server'); -}); + ```typescript + const socket = io(); // Automatically connects to the server + ``` -socket.on('disconnect', () => { - console.log('Disconnected from the server'); -}); -``` + Server-Side: + On the server, Socket.IO will create a `socket` object for each client that connects. You can listen for new connections with the `io.on('connection')` event: -3. Emitting an Update + Object with the Update\ -To send data from the client to the server or vice versa, you use the `.emit()` method. -Example: Emitting a Custom Event -Let's say we want to send a chat message from the client to the server. You can emit a custom event like this: -``` -// Client-side -socket.emit('chat message', { user: 'John', message: 'Hello, World!' }); -``` -On the server side, you can listen for this event and handle the received data: -``` -// Server-side -socket.on('chat message', (data: { user: string; message: string }) => { - console.log(`${data.user}: ${data.message}`); -}); -``` -You can also send data back to all connected client: -``` -// Server-side -io.emit('chat message', { user: 'Server', message: 'Welcome to the chat!' }); -``` + ```typescript + io.on("connection", (socket: Socket) => { + console.log("A user connected"); + }); + ``` -4. Subscribing a Listener to an Update + Handler Function for Emitted Object\ -On the client side, you need to subscribe to the event to receive the emitted messages: -``` -// Client-side -socket.on('chat message', (data: { user: string; message: string }) => { - console.log(`${data.user}: ${data.message}`); -}); -``` -This will allow the client to receive and handle chat messages sent from the server (or other clients). +2. **Setting Up a Connection** -Putting It All Together -Here's an example of a simple chat app: -Server-Side (`server.ts`)" -``` -io.on('connection', (socket) => { - console.log('A user connected'); + Once the socket object is created, both the client and server can start emitting and receiving events. + + Example: Handling Connections and Disconnections + + We can already see basic connection handling: + + ```typescript + // Server-side + io.on("connection", (socket: Socket) => { + console.log("A user connected"); + + socket.on("disconnect", () => { + console.log("A user disconnected"); + }); + }); + ``` + + On the client-side, you can also listen for the `connect` and `disconnect` events: + + ```typescript + // Client-side + socket.on("connect", () => { + console.log("Connected to the server"); + }); - socket.on('chat message', (data: { user: string; message: string }) => { + socket.on("disconnect", () => { + console.log("Disconnected from the server"); + }); + ``` + +3. **Emitting an Update + Object with the Update** + + To send data from the client to the server or vice versa, you use the `.emit()` method. + + Example: Emitting a Custom Event + + Let's say we want to send a chat message from the client to the server. You can emit a custom event like this: + + ```typescript + // Client-side + socket.emit("chat message", { user: "John", message: "Hello, World!" }); + ``` + + On the server-side, you can listen for this event and handle the received data: + + ```typescript + // Server-side + socket.on("chat message", (data: { user: string; message: string }) => { + console.log(`${data.user}: ${data.message}`); + }); + ``` + + You can also send data back to all connected clients: + + ```typescript + // Server-side + io.emit("chat message", { user: "Server", message: "Welcome to the chat!" }); + ``` + +4. **Subscribing a Listener to an Update + Handler Function for Emitted Object** + + On the client-side, you need to subscribe to the event to receive the emitted messages: + + ```typescript + // Client-side + socket.on("chat message", (data: { user: string; message: string }) => { + console.log(`${data.user}: ${data.message}`); + }); + ``` + + This will allow the client to receive and handle chat messages sent from the server (or other clients). + +## Putting It All Together + +Here's an example of the sockets in a simple chat app: + +Server-Side (`server.ts`): + +```typescript +io.on("connection", (socket) => { + console.log("A user connected"); + + socket.on("chat message", (data: { user: string; message: string }) => { console.log(`${data.user}: ${data.message}`); // Broadcast the message to all clients - io.emit('chat message', data); + io.emit("chat message", data); }); - socket.on('disconnect', () => { - console.log('A user disconnected'); + socket.on("disconnect", () => { + console.log("A user disconnected"); }); }); ``` + Client-Side (`index.html`): -``` + +```html ``` -This example sets up a basic chat app where users can send and receive messages in real time. +This example sets up a basic chat app where users can send and receive messages in real time. # Useful Resources