lensh / vue-qq

🎨 Vue family bucket with socket.io and express/koa2 , create a web version of mobile QQ, supporting real-time group chat, real-time private chat, special care, shielding chat, smart IP geographic location, real-time display temperature and other QQ core functions
MIT License
916 stars 232 forks source link

请问koa2如何实现socket.io? #22

Open l20 opened 7 years ago

l20 commented 7 years ago

我代码是这样的:

const Koa = require('koa');
const app = new Koa();
const server = require('http').Server(app.callback());
const io = require('socket.io')(server);

io.on('connection', function(socket){
  io.emit('this', { will: 'be received by everyone'});

  socket.on('private message', function (from, msg) {
    console.log('I received a private message by ', from, ' saying:', msg);
  });

  socket.on('disconnect', function () {
    io.emit('user disconnected');
  });

});

但是前端请求的时候找不到数据,该如何做呢,希望提供ko2的一些源码。

lensh commented 7 years ago

const server = require('http').Server(app.callback()); 改成 const server = require('http').createServer(app.callback());

l20 commented 7 years ago

@lensh 还是不行啊,浏览器打印这要的错误,是什么原因请求不到呢?


socket.io.js:2 XHR finished loading: GET "http://localhost:3001/socket.io/?EIO=3&transport=polling&t=LwZ9ZPG".
i.create @ socket.io.js:2
i @ socket.io.js:2
o.request @ socket.io.js:2
o.doPoll @ socket.io.js:2
r.poll @ socket.io.js:2
r.doOpen @ socket.io.js:2
r.open @ socket.io.js:2
r.open @ socket.io.js:1
r @ socket.io.js:1
r @ socket.io.js:1
r.open.r.connect @ socket.io.js:1
(anonymous) @ socket.io.js:1
socket.io.js:2 GET http://localhost:3001/socket.io/?EIO=3&transport=polling&t=LwZ9ae6 404 (Not Found)
i.create @ socket.io.js:2
i @ socket.io.js:2
o.request @ socket.io.js:2
o.doPoll @ socket.io.js:2
r.poll @ socket.io.js:2
r.doOpen @ socket.io.js:2
r.open @ socket.io.js:2
r.open @ socket.io.js:1
r @ socket.io.js:1
r @ socket.io.js:1
r.open.r.connect @ socket.io.js:1
(anonymous) @ socket.io.js:1
socket.io.js:2 XHR finished loading: GET "http://localhost:3001/socket.io/?EIO=3&transport=polling&t=LwZ9ae6".
lensh commented 7 years ago

404不是已经很明显了吗?你看看端口是否一致,看服务端的代码是不是监听的3001端口。。。实在不行的话,你提供一下你项目的github地址吧,我再帮你看看。。。

l20 commented 7 years ago

@lensh 感谢回答,是其他问题,错误找到了。

harry-code commented 3 years ago

同样遇到,请问大佬是怎么解决的呢?