Create and Run a Socket.io Project
What is Socket.io?
Socket.io is a JavaScript library for real-time, bidirectional, event-driven communication. It can establish efficient, low-latency communication channels between browser and server. Socket.io supports the WebSocket protocol but is not limited to it, as it can automatically select the best transport mechanism (such as long polling) to ensure connection stability.
Main Features and Advantages of Socket.io
- Real-time Communication: Supports real-time bidirectional communication, suitable for chat rooms, online games, real-time notifications, and other application scenarios.
- Cross-Platform Support: Can run in browsers, Node.js, and other platforms.
- Auto-Reconnect: Automatically tries to reconnect when the connection is lost.
- Event-Driven: Uses an event-driven mechanism for communication, simplifying the programming model.
- High Compatibility: Supports various transport mechanisms like WebSocket, XHR long polling, etc., ensuring normal operation in various network environments.
Using Socket.io can help developers quickly build efficient real-time communication applications.
Create and Run a Socket.io Project Using ServBay
In this article, we will use the Node.js environment provided by ServBay to create and run a Socket.io project. We'll use ServBay's "Host" feature to set up a web server and enable project access through reverse proxy.
Creating the Socket.io Project
Initialize the Project
First, ensure you have already installed the Node.js environment provided by ServBay. Then, create a new Socket.io project in the recommended site root directory
/Applications/ServBay/www
:bashcd /Applications/ServBay/www mkdir servbay-socketio-app cd servbay-socketio-app npm init -y npm install express socket.io
1
2
3
4
5Create Server File
Create a
server.js
file in the project root directory and add the following code:javascriptconst express = require('express'); const http = require('http'); const socketIo = require('socket.io'); const app = express(); const server = http.createServer(app); const io = socketIo(server); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); io.on('connection', (socket) => { console.log('a user connected'); socket.on('disconnect', () => { console.log('user disconnected'); }); socket.on('chat message', (msg) => { io.emit('chat message', msg); }); }); const port = process.env.PORT || 3000; server.listen(port, () => { console.log(`Server running on port ${port}`); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26Create Client File
Create an
index.html
file in the project root directory and add the following code:html<!DOCTYPE html> <html> <head> <title>Socket.io Chat with ServBay</title> <style> ul { list-style-type: none; padding: 0; } li { padding: 8px; margin-bottom: 10px; background-color: #f3f3f3; } input { padding: 10px; width: 300px; } button { padding: 10px; } .servbay-banner { background-color: #4CAF50; color: white; text-align: center; padding: 10px 0; font-size: 20px; margin-bottom: 20px; } </style> </head> <body> <div class="servbay-banner">Welcome to ServBay Socket.io Chat!</div> <ul id="messages"></ul> <form id="form" action=""> <input id="input" autocomplete="off" /><button>Send</button> </form> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); var form = document.getElementById('form'); var input = document.getElementById('input'); form.addEventListener('submit', function(e) { e.preventDefault(); if (input.value) { socket.emit('chat message', input.value); input.value = ''; } }); socket.on('chat message', function(msg) { var item = document.createElement('li'); item.textContent = msg; document.getElementById('messages').appendChild(item); window.scrollTo(0, document.body.scrollHeight); }); </script> </body> </html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
Enter Development Mode
Run Development Server
Start the development server and specify the port (e.g., 8585):
bashPORT=8585 node server.js
1This will start a local development server and expose port 8585.
Configure ServBay Host Reverse Proxy
Use ServBay's "Host" feature to access the development server through reverse proxy. In the ServBay "Host" settings, add a new reverse proxy:
- Name:
My first Socket.io dev site
- Domain:
servbay-socketio-test.dev
- Host Type:
Reverse Proxy
- IP:
127.0.0.1
- Port:
8585
For detailed setup steps, refer to Adding Node.js Development Website.
- Name:
Access Development Mode
Open the browser and visit
https://servbay-socketio-test.dev
to view the project in real time. Since ServBay supports custom domains and free SSL certificates, you will enjoy higher security.
Deploy Production Version
Prepare Production Environment
Ensure your project can run normally in the production environment. Typically, a Socket.io project doesn't require special build steps, but you may need to set some environment variables or perform other configurations.
Run Production Server
Start the production server and specify the port (e.g., 8586):
bashPORT=8586 NODE_ENV=production node server.js
1Configure ServBay Host Reverse Proxy
Use ServBay's "Host" feature to access the production server through reverse proxy. In the ServBay "Host" settings, add a new reverse proxy:
- Name:
My first Socket.io production site
- Domain:
servbay-socketio-test.prod
- Host Type:
Reverse Proxy
- IP:
127.0.0.1
- Port:
8586
- Name:
Access Production Mode
Open the browser and visit
https://servbay-socketio-test.prod
to view the production version. With ServBay's custom domain and free SSL certificate, your site will have higher security and credibility.
Database Connection
ServBay provides support for Redis, MariaDB, PostgreSQL, and MongoDB databases. Here are examples of how to connect to these databases.
Connect to MongoDB
Install
mongoose
:bashnpm install mongoose
1Then introduce and connect in the project:
javascriptconst mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/servbay-socketio-app', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected')) .catch(err => console.log(err));
1
2
3
4
5Connect to Redis
Install
redis
:bashnpm install redis
1Then introduce and connect in the project:
javascriptconst redis = require('redis'); const client = redis.createClient(); client.on('error', function (err) { console.log('Error ' + err); }); client.on('connect', function () { console.log('Redis client connected'); });
1
2
3
4
5
6
7
8
9
10Connect to MariaDB
Install
mariadb
:bashnpm install mariadb
1Then introduce and connect in the project:
javascriptconst mariadb = require('mariadb'); const pool = mariadb.createPool({ host: 'localhost', user: 'root', password: 'password', database: 'servbay_socketio_app' }); pool.getConnection() .then(conn => { console.log("Connected to MariaDB"); conn.release(); //release to pool }) .catch(err => { console.log("Not connected due to error: " + err); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16Connect to PostgreSQL
Install
pg
:bashnpm install pg
1Then introduce and connect in the project:
javascriptconst { Pool } = require('pg'); const pool = new Pool({ user: 'user', host: 'localhost', database: 'servbay_socketio_app', password: 'password', port: 5432, }); pool.connect((err, client, done) => { if (err) throw err; console.log('Connected to PostgreSQL'); done(); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Through the above steps, you have successfully created and run a Socket.io project, managed and accessed your project using ServBay's features, and connected to various databases.