简体   繁体   English

websocket socket.io dir nodejs

[英]websocket socket.io dir nodejs

I have a question regarding socket.io and dir我对 socket.io 和目录有疑问

I have an api to validate login / jwt and etc我有一个 api 来验证登录 / jwt 等

I'm starting to create a websocket server to create a joken po game, one question i already have this api folder, should i create my websocket server inside this src?我开始创建一个websocket服务器来创建一个joken po游戏,一个问题我已经有了这个api文件夹,我应该在这个里面创建我的websocket服务器吗? Or is it better to create another folder for this separate websocket server and it will consume my login api and others dates还是为这个单独的 websocket 服务器创建另一个文件夹更好,它将消耗我的登录 api 和其他日期

and about having to pass html directory on nodejs to use socketio ex:以及必须通过 nodejs 上的 html 目录才能使用 socketio ex:

webApp.get ('/', (req, res, next) => {
res.sendFile (__ dirname + 'game.html'
});

How would I do if I create in a separate folder from my front end how would I be able to communicate?如果我在与前端不同的文件夹中创建,我将如何进行通信? ex: my front end in front end folder my back end in backend folder例如:我在前端文件夹中的前端 我在后端文件夹中的后端

You can use your existing express server to host your socket.io instance.您可以使用现有的快速服务器来托管您的 socket.io 实例。 You can reuse all the same infrastructure in place and continue to use jwt tokens for your authentication with socket.io.您可以重用所有相同的基础设施,并继续使用 jwt 令牌进行 socket.io 的身份验证。 Look at the socketio-jwt package on npm.看npm上的socketio-jwt package。

const socketioJwt = require('socketio-jwt');
const express = require('express');
const app = express();

// rest of your express config
...

const server = app.listen(PORT,
  console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);

const io = require('socket.io')(server);
io.use(socketioJwt.authorize({
  secret: 'your secret or public key',
  handshake: true
}));

io.on('connection', (socket) => {
  console.log('hello!', socket.decoded_token.name);

  socket.emit('hello', {message: 'hello world'});

  socket.on('myevent', myhandler);
});

Ideally, you can simply use socket.io for all your backend communication.理想情况下,您可以简单地使用 socket.io 进行所有后端通信。

In react you would simply import the socket.io client and then connect as follows:在反应中,您只需导入socket.io 客户端,然后按如下方式连接:

let socket = null;

function App() {

  useEffect(() => {

    async function connect () {
       socket = io.connect('http://myserver');
    }
    connect();

  }, []);

  return (
    <div>
       Hello
    </div>
  );
}

export default App;

There is a lot to cover and it is a broad question, but you have some starting points now to continue your research.有很多内容要涵盖,这是一个广泛的问题,但是您现在有一些起点可以继续您的研究。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM