bdwain
bdwain

Reputation: 1745

How do I trigger a real time client update in Rails

I'm creating an online multiplayer board game using Rails, and I want the game to be able to be played without having to manually refresh the page. I'm planning on using websockets or Server Sent Events's to update the page. I haven't decided which yet, but I don't expect it to make a difference for my question.

The thing I'm confused about is knowing when to send an update to the client. For example, let's say I was making chess, and player1 took a turn. They would send up their move to the server, the server would then save it to the database. How does player2's websocket or SSE know to push the info about player1's move to player2's brower?

I know they could regularly query the database to see if the game has been updated, but that seems like it would be hard to scale since every user would be querying the database very often.

Is there an easy way to wait for an update to the database and be notified of it automatically somehow? Or are there other solutions?

I've looked around online a bunch for solutions to this, but haven't really gotten any concrete ideas. I'm definitely open to using a library or whatever to solve the problem as long as it's free. I've seen some paid solutions but those aren't an option.

I also saw someone suggest somehow using node.js alongside rails to do something with realtime. I don't know much about node.js, but I have heard it's good for asynchronous functionality like that. I'd be interested in learning how to use it if it's better than any rails solution.

I'm using Rails 3.2, but if Rails 4 has something that would work well here, I'd probably be interested in that as well.

Upvotes: 0

Views: 1434

Answers (2)

AndyD
AndyD

Reputation: 5385

As nik suggested, use the FAYE Ruby Server if you're a ruby developer.

In terms of how things could hang together:

  1. Each game is a channel
  2. Each player subscribes to this channel
  3. When a player makes a move, the move is sent to the server
  4. The server saves the move against the game in the db
  5. The server sends a message to the channel.
  6. Both player's ui update with the new move.

This setup allows you to easily replay a whole game or continue where you left off. Just get all moves from db and send them in order to a new channel. This might not be performant, but it should work.

Upvotes: 2

nik7
nik7

Reputation: 3058

you can also use FAYE which has Ruby Server and Node.js server, you can choose one

Upvotes: 0

Related Questions