我已经构建了一个客户端 - 服务器Web套接字应用程序。
我面临的问题是,当服务器收到连接时,客户端仍然无法连接。
let restify = require('restify')
let server = restify.createServer()
let socketio = require('socket.io')
server.use(restify.bodyParser())
server.use(restify.queryParser())
server.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
next()
})
//Adding routes here
server.listen(3000, function () {
console.log('%s listening at %s', server.name, server.url)
})
let websocket = socketio.listen(server.server, { path: '/api/chat/connect', origins: 'http://localhost:* http://127.0.0.1:*' });
websocket.on('connection', (socket) => {
// I see this log when the client connects
console.log('new client connected')
socket.on('disconnect', () => {
// I see this log when the client disconnects
console.log('Client disconnected.');
});
})
//Test connection
websocket.emit('new-message', { message: 'Connection done!!!' })
let io = require('socket.io-client')
let socket = io.connect('http://localhost:3000/api/chat/connect', { path:'/api/chat/connect', reconnect: true, forceNew: true })
//Debugging here I noticed that socket.connected == false
//Intent 1
socket.on('new-message', (data) => {
//Nothing happening here
})
//Intent 2
socket.on('connect', function(){
//Nothing happening here
socket.on('new-message', function(data){
//Nothing happening here
});
});
//Intent 3
socket.on('new-message', (data) => {
//Nothing happening here
})
socket.connect()
从客户端呼叫io.connect
连接后,服务器正确接收连接。但是在io.connect
之后立即调试,我注意到了socket.connected == false
。
{
"dependencies": {
... stuff
"restify": "4.1.x",
"socket.io": "^1.7.3"
... stuff
},
"engines": {
"node": "0.8.x"
}
}
{
... stuff
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-redux": "^5.0.3",
"react-router": "^3.0.2",
"redux": "^3.6.0",
"redux-thunk": "^2.2.0",
"socket.io-client": "^1.7.3"
},
... stuff
}
答案 0 :(得分:0)
它可能是命名空间的缺失设置。为了解决这个问题,您需要在服务器端为路径“/ api / chat / connect”设置一个自定义命名空间,如下所示:
let websocket = socketio.listen(server.server, { path: '/api/chat/connect', origins: 'http://localhost:* http://127.0.0.1:*' });
let nsp = websocket.of('/api/chat/connect');
nsp.on('connection', (socket) => {
// I see this log when the client connects
console.log('new client connected')
socket.on('disconnect', () => {
// I see this log when the client disconnects
console.log('Client disconnected.');
});
})
您可以在此处找到有关自定义命名空间的更多信息
https://socket.io/docs/rooms-and-namespaces/#custom-namespaces
运行服务器端代码时,请尝试在“DEBUG = socket.io *”前加上查看socket.io发出的日志
e.g。在你的package.json脚本
中scripts:{
start: "DEBUG=socket.io* node index.js",
...
}