server.js 826 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. const app = require('./app')
  2. const fs = require('fs')
  3. require.extensions['.nes'] = function(module, filename) {
  4. module.exports = fs.readFileSync(filename, 'binary')
  5. }
  6. const SMB = require('../common/smb')
  7. game = new SMB()
  8. console.log(game.start.toString())
  9. game.start()
  10. app.ws('/game', (ws, req) => {
  11. const send = (frame) => {
  12. try {
  13. ws.send(JSON.stringify(game.gameState()))
  14. ws.send(frame)
  15. } catch(err) {
  16. console.warn(err.message)
  17. teardown()
  18. }
  19. }
  20. const frameSub = game.frames.subscribe(send)
  21. const teardown = () => {
  22. console.log('Detaching')
  23. frameSub.unsubscribe()
  24. }
  25. ws.on('message', (msg) => {
  26. const data = JSON.parse(msg)
  27. game.command(data)
  28. })
  29. ws.on('close', teardown)
  30. })
  31. app.listen().catch((err) => {
  32. console.log(err.toString())
  33. process.exit(1)
  34. })