简体   繁体   中英

websocket socket.io dir nodejs

I have a question regarding socket.io and dir

I have an api to validate login / jwt and etc

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? Or is it better to create another folder for this separate websocket server and it will consume my login api and others dates

and about having to pass html directory on nodejs to use 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. You can reuse all the same infrastructure in place and continue to use jwt tokens for your authentication with socket.io. Look at the socketio-jwt package on npm.

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.

In react you would simply import the socket.io client and then connect as follows:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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