I'm more or less following the socket.io documentation and trying to apply it to my slightly different project but I believe I'm making some mistake. I've used express-generator to create my project's skeleton and therefore I got app.js file, www file and route files.
我或多或少跟在插座上。io文档并试图将其应用到我的略有不同的项目中,但我认为我犯了一些错误。我使用了express-generator来创建项目的框架,因此获得了app.js文件、www文件和路由文件。
I've put this code in www file:
我把这段代码放在www文件中:
var io = require('socket.io')(http);
console.log('Socket is running!');
io.on('connection', function(socket){
console.log('A User Has Connected: ' + socket.id);
});
This code in my footer file:
我的页脚文件中的代码:
<script src="/socket.io/socket.io.js"></script>
<script src="/javascripts/jquery-3.2.1.min.js"></script>
<script src="/javascripts/javascript.js"></script>
</body>
</html>
And this in my JavaScript file:
在我的JavaScript文件中:
$(document).ready(function(){
var socket = io();
});
Now I understand that when a request is made, the console should log "A User Has Connected: " + the id of the socket but I'm not getting anything other than "Socket is running!". I assume I'm missing something but can't figure it out and the documentation is using the same code.
现在我明白了,当发出请求时,控制台应该记录“用户已连接:”+套接字的id,但除了“套接字正在运行!”我假设我漏掉了一些东西,但是我想不出来,文档使用的是相同的代码。
var port = normalizePort(process.env.PORT || '8087');
app.set('port', port);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
1 个解决方案
#1
2
You have to use the same server instance express-generator
creates, which is the following line in www
file
您必须使用相同的服务器实例express-generator create,这是www文件中的如下一行
var server = http.createServer(app);
To use that, change
使用,改变
var io = require('socket.io')(http);
to
来
var io = require('socket.io')(server);
#1
2
You have to use the same server instance express-generator
creates, which is the following line in www
file
您必须使用相同的服务器实例express-generator create,这是www文件中的如下一行
var server = http.createServer(app);
To use that, change
使用,改变
var io = require('socket.io')(http);
to
来
var io = require('socket.io')(server);