我发现教程中的编码指向在localhost中运行一个简单的socket.io聊天服务器,我安装了必要的环境,如nodejs,express,init package.json,我使用命令“node app.js”从终端启动服务器“,然后我在我的localhost中访问了索引页面,它显示了聊天页面,它运行正常。但事情是我想用这个在我的办公室的实时服务器,在办公室内聊天。这段代码是否足够。我是这个socket.io和nodejs的新手。我的办公室有用于托管其网站的实时服务器,此代码打开并侦听端口3000.如果您能告诉我如何在真实服务器中运行它,将会非常有用。
的index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
</head>
<script src = "/socket.io/socket.io.js"></script>
<script>
var socket = io();
function setUsername() {
socket.emit('setUsername', document.getElementById('name').value);
};
var user;
socket.on('userExists', function(data) {
document.getElementById('error-container').innerHTML = data;
});
socket.on('userSet', function(data) {
user = data.username;
document.body.innerHTML = '<input type = "text" id = "message">\
<button type = "button" name = "button" onclick = "sendMessage()">Send</button>\
<div id = "message-container"></div>';
});
function sendMessage() {
var msg = document.getElementById('message').value;
if(msg) {
socket.emit('msg', {message: msg, user: user});
}
}
socket.on('newmsg', function(data) {
if(user) {
document.getElementById('message-container').innerHTML += '<div><b>' +
data.user + '</b>: ' + data.message + '</div>'
}
})
</script>
<body>
<div id = "error-container"></div>
<input id = "name" type = "text" name = "name" value = ""
placeholder = "Enter your name!">
<button type = "button" name = "button" onclick = "setUsername()">
Let me chat!
</button>
</body>
</html>
app.js服务器
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendfile('index.html');
});
users = [];
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('setUsername', function(data) {
console.log(data);
if(users.indexOf(data) > -1) {
socket.emit('userExists', data + ' username is taken! Try some
} else {
users.push(data);
socket.emit('userSet', {username: data});
}
});
socket.on('msg', function(data) {
//Send message to everyone
io.sockets.emit('newmsg', data);
})
});
http.listen(3000, function() {
console.log('listening on localhost:3000');
});
答案 0 :(得分:2)
您可以通过nginix(反向代理服务器)解决您的问题。 Nginx有.conf文件,其中包含服务器实现的配置。
server { listen 3000; server_name io.yourhost.com; }
运行:
Sudo service nginx start
它将以给定的IP或域名启动您的服务器。
答案 1 :(得分:1)
更改声明变量套接字
var socket = io(Server IP + ':port');
示例:
var socket = io('127.0.0.1:3000);
我使用socket.io版本2.0.2