我是NodeJs的新手。我正在网上关于如何制作socket.io(聊天应用程序)的教程。我创建了一个脱机工作的简单应用程序,但是为了使它工作,我必须转到命令提示符,进入我的项目并输入:节点服务器:在端口上启动服务器3000。
我想把这个小应用程序放到我的网站上,我做了here
但是当我尝试在聊天框中输入内容时,它不会显示,并且它在控制台中给了我一堆错误。我知道它可能与端口有关。我只是不知道如何在现场网站上运行它。
这是我的服务器端代码:
// Include all of our modules
var express = require('express');
// Set variable "app" = to the 'express' variable
var app = express();
// Set our server variable, and pass in 'app' variable
var server = require('http').createServer(app);
// Include socket.io and listen to the 'server' variable
var io = require('socket.io').listen(server);
// * We are going to have 2 arrays
// One for users, other one for connections
users = [];
connections = [];
// Run the server, and listen to assigned port
server.listen(process.env.PORT || 3000);
console.log('Server running...');
// Create a route, a function is going to take in a "request" and a "response"
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
// Open a connection with socket.io
io.sockets.on('connection', function(socket) {
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
// Write our disconnect, and console.log how many are still connected
socket.on('disconnect', function (data) {
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: %s sockets connected', connections.length);
});
// Send message
socket.on('send message', function (data) {
// emmit a new message event
io.sockets.emit('new message', {msg: data});
})
});
这是我的客户端代码:
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="well">
<h4>Online Users</h4>
<ul class="list-group" id="users"></ul>
</div>
</div>
<div class="col-md-8">
<div class="chat" id="chat"></div>
<form id="messageForm">
<div class="form-group">
<label>Enter a message</label>
<textarea class="form-control" id="message"></textarea>
<br />
<input type="submit" class="btn btn-primary" value="Send Message">
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(function() {
var socket = io.connect();
var $messageForm = $('#messageForm');
var $message = $('#message');
var $chat = $('#chat');
// create a event when form is submitted
$messageForm.submit(function(e) {
e.preventDefault();
socket.emit('send message', $message.val());
$message.val('');
});
socket.on('new message', function(data) {
$chat.append('<div class="well">'+data.msg+'</div>');
});
});
</script>
答案 0 :(得分:0)
socket.io自动配置其连接
准确地说,我总是将网址传递给io.connect (more info)
var socket = io.connect('http://<website_name>:<port>/');
例如在您的情况下:
var socket = io.connect('http://davidtrushkov.com:3000/');