我有一个路径http://localhost:3000/home/我想创建一个套接字连接。 我index.jsio.connect到特定的路径节点js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var path = require("path");
var io = require('socket.io')(http);
app.get('*', function (req, res){
res.sendFile(path.join(__dirname, '/Public'));
});
app.use('/home',express.static(path.join(__dirname,'/Public')));
//app.use('/static', express.static(__dirname + 'index.html'));
io.on('connection', function (socket) {
socket.on('message', function (data) {
console.log(data)
socket.emit('news', { hello: 'world' });
});
socket.on('another-message', function (data) {
socket.emit('not-news', { hello: 'world' });
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
我的index.html
<html>
<h1>working</h1>
<script src="/socket.io/socket.io.js"></script>
<script src ="script.js"></script>
<body>
<ul id="messages"></ul>
<form id ="target" action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
我的脚本文件
var socket = io.connect('http://localhost:3000',{path:'/home/socket.io});
socket.on('connect',function(){
socket.emit('message', 'Hello server');
});
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
当我运行 “http://localhost:3000/home/” 我得到的错误
请求URL: http://localhost:3000/home/socket.io/?EIO=3&transport=polling&t=LAN0qOj 请求方法:GET 状态代码:404未找到 远程地址:[:: 1]:3000
请纠正我。
看到这个答案http://stackoverflow.com/questions/29511404/connect-to-socket-io-server-with-specific-path-and-namespace –
@doron aviguy我不喜欢的东西是笏我在index.js中提到“var io = require('socket.io')(http,{path:'/myapp/socket.io'});”但是现在我得到了错误GET http:// localhost:3000/socket.io/socket.io.js (index):6未捕获的ReferenceError:io未定义(匿名函数)@(index):6现在导入socket.io失败,它说io未定义 –
'require('socket.io')(http,{path:''/myapp/socket.io“})' –