A simple socket.io project with Rooms feature
A Socket.IO room is an arbitrary channel that sockets can join and leave. It can be used to broadcast events to a subset of clients. See here
To get a local copy up and running follow these simple example steps.
Node.js is a JavaScript runtime that allows you to run JavaScript code on the server-side. You can think of it as the JavaScript runtime (e.g. console) from the web browser (e.g. Chrome) ripped out and made available for web servers. If you haven't already, head along to https://nodejs.org and install Node on your machine.
- check node version
node -v
- npm
npm install npm@latest -g
- check npm version
npm is the standard package manager for Node.js. npm installs, updates and manages downloads of dependencies of your project. Dependencies are pre-built pieces of code, such as libraries and packages, that your Node.js application needs to work.
npm -v
- Clone the repository
git clone https://github.com/AylexCODE/SocketIO.git
- Install NPM packages
npm install
- Start server
The output should be
node .Socket is listening... at port [PORT]
include the client bundle from a CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.8.1/socket.io.min.js"></script>Localhost
const socket = io();Non-Local Host
const socket = io("URL");socket.on('connect', () => {
console.log("Connected!");
});
socket.on('disconnect', () => {
console.log("Disconnected!");
});- Send event to a server
socket.emit(event, ...args);
// example: 'sendMessage' event
socket.emit("sendMessage", "World");- Listen for events sent by a server
socket.on(event, ...args);
// example: 'recieveMessage' event
socket.on('recieveMessage', (message) => {
console.log(message);
});- Listen for an event sent by a client
socket.on(event, ...args);
// example: listen for an event named 'sendMessage' sent by a client
socket.on("sendMessage", (message) => {
console.log(message);
}- Send an event to a client
socket.emit(event, ...args);
// example: send an event named 'recieveMessage' to a client
socket.emit("receiveMessage", "Hi");Refer to Socket.IO for more info.
That's all. Don't forget to give the project a star! Thank you for visiting.