如何在在线服务器上为已部署的CodeIgniter应用集成安装Node.js
Hey there! Let's walk through getting Node.js set up and integrating Socket.io with your CodeIgniter app on your live server — I've done this a few times, so I'll break it down into simple, actionable steps.
Step 1: Install Node.js on Your Server
The most flexible way to manage Node.js versions (and avoid system-wide conflicts) is using nvm (Node Version Manager). Here's how to set it up for common server distros:
For Ubuntu/Debian-based servers:
- Update your package list and install curl:
sudo apt update && sudo apt install curl -y - Install nvm via its official script:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash - Load nvm immediately (or close/reopen your terminal):
source ~/.bashrc - Install the latest stable LTS version of Node.js (best for production):
nvm install --lts - Verify the installation worked:
node -v && npm -v
For CentOS/RHEL-based servers:
- Install curl first:
sudo yum install curl -y - Follow the same nvm installation steps above, then install the LTS Node.js version.
If you prefer a system-wide install without nvm, you can use your distro's package manager, but nvm makes future version updates way simpler.
Step 2: Set Up Your Socket.io Server
Create a dedicated folder for your Socket.io server (you can keep it separate from your CodeIgniter project for cleaner organization):
- Initialize a new Node.js project:
mkdir socket-server && cd socket-server npm init -y - Install required dependencies:
npm install socket.io express cors body-parser - Create a
server.jsfile with this basic real-time server setup:
Don't forget to replaceconst express = require('express'); const http = require('http'); const { Server } = require('socket.io'); const cors = require('cors'); const bodyParser = require('body-parser'); const app = express(); app.use(cors()); app.use(bodyParser.json()); const server = http.createServer(app); const io = new Server(server, { cors: { origin: "https://your-codeigniter-domain.com", // Replace with your CI app's URL methods: ["GET", "POST"] } }); // Handle client connections io.on('connection', (socket) => { console.log('User connected:', socket.id); // Listen for incoming chat messages socket.on('send_chat', (data) => { // Broadcast message to all connected clients io.emit('receive_chat', data); }); socket.on('disconnect', () => { console.log('User disconnected:', socket.id); }); }); // Optional: Endpoint to trigger messages from CodeIgniter backend app.post('/trigger-notification', (req, res) => { const notification = req.body; io.emit('receive_chat', notification); res.status(200).json({ success: true }); }); // Start server on port 3000 (adjust if needed) const PORT = 3000; server.listen(PORT, () => { console.log(`Socket.io server running on port ${PORT}`); });https://your-codeigniter-domain.comwith your actual CodeIgniter app URL to avoid cross-origin errors.
Step 3: Connect CodeIgniter to Socket.io
Link your CodeIgniter frontend (and optionally backend) to the Socket.io server:
Frontend Integration (in CodeIgniter views):
Add the Socket.io client library and connection logic to your chat view:
<!-- Load Socket.io client via CDN --> <script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script> <script> // Connect to your Socket.io server const socket = io('https://your-server-ip:3000'); // Replace with your server's IP/domain + port // Send message on button click document.getElementById('send-btn').addEventListener('click', () => { const message = document.getElementById('chat-input').value; const username = '<?= $this->session->userdata('username') ?>'; // Get user from CI session if (message.trim()) { socket.emit('send_chat', { username, message }); document.getElementById('chat-input').value = ''; } }); // Receive and display incoming messages socket.on('receive_chat', (data) => { const chatContainer = document.getElementById('chat-box'); chatContainer.innerHTML += `<div class="chat-message"><strong>${data.username}:</strong> ${data.message}</div>`; // Scroll to bottom of chat chatContainer.scrollTop = chatContainer.scrollHeight; }); </script>
Backend Integration (optional, for server-triggered messages):
If you need to send real-time updates from CodeIgniter (e.g., admin notifications), make an HTTP request to your Socket.io server from a CI controller:
public function send_admin_notification() { $notification = [ 'username' => 'Admin', 'message' => 'A new support ticket has been submitted!' ]; $ch = curl_init('http://localhost:3000/trigger-notification'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notification)); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); $response = curl_exec($ch); curl_close($ch); return $this->output->set_content_type('application/json')->set_output($response); }
Step 4: Keep the Socket.io Server Running
You don't want your real-time server to stop when you close your terminal. Use pm2 (a Node.js process manager) to keep it running in the background:
- Install pm2 globally:
npm install pm2 -g - Start your Socket.io server with pm2:
pm2 start server.js --name "socket-server" - Set pm2 to start automatically on server boot:
Follow the on-screen instructions to save the startup script.pm2 startup - Check server status anytime:
pm2 status
Final Checks
- Open your server's firewall for the Socket.io port (3000 by default). For Ubuntu:
sudo ufw allow 3000/tcp - Test the chat feature by opening your CodeIgniter app in multiple browsers — messages should appear in real-time across all sessions.
内容的提问来源于stack exchange,提问作者Gulzar

