要在CentOS上搭建聊天服務器,您可以按照以下步驟進行操作:
安裝必要的軟件:
sudo yum install nginx
sudo yum install nodejs
sudo yum install npm
配置Nginx:
sudo vi /etc/nginx/nginx.conf
upstream chat {
server localhost:3000;
keepalive 8;
}
server {
listen 80;
server_name your_domain.com;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://chat;
proxy_redirect off;
}
}
sudo systemctl restart nginx
下載和設置聊天服務器:
mkdir chat-server && cd chat-server
npm install socket.io
server.js
,并添加以下內容:const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('A user connected!');
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('A user disconnected!');
});
});
server.listen(3000, () => {
console.log('Chat server listening on *:3000');
});
啟動聊天服務器:
node server.js
現在,您的聊天服務器已經搭建完成。您可以使用Web瀏覽器訪問您的服務器域名(或IP地址),并與其他用戶進行實時聊天。