When an event or function is processed instantaneously, it is said to occur in real-time. To say something takes place in real-time is the same as saying it is happening 'live' or 'on-the-fly.' For example, the graphics in a 3D action game are rendered in real-time by the computer's video card. This means the graphics are updated so quickly, there is no noticeable delay experienced by the user. While some computer systems may be capable of rendering more frames per second than other systems, the graphics are still being processed in real-time.
Total War: Arena is the upcoming free-to-play Team-based real time strategy game from The Creative Assembly. The game is in closed alpha and closed beta stage now, and will be released soon. Total War: Arena mixes genres such as multiplayer online battle arena and real-time strategy together and features 10vs10 (PvP) battles. Real Time Tactics (RTT) is a sub-genre of strategy games and an immensely popular one too. RTT games have always kept the spotlight and at times have shown the potential to outsell real time strategy games. What makes these games so popular is the use of real-world war concepts: holding the line and executing your tactical moves to outsmart the opponent with minimum resources. Total War: Shogun 2. Unsurprisingly, if we look at any online list of best real time strategy games, we.
While video games often require real-time rendering, not all graphics are rendered in real-time. For example, some complex 3D models and animations created for movies are not rendered in real-time, but instead are pre-rendered on a computer system so they can be played back in real-time. As graphics cards get increasingly faster, they are capable of rendering some 3D animations in real-time that previously would need to be pre-rendered.
Real-time also describes the way streaming media is processed. Instead of waiting for a file to completely download, the information is played back as it is downloaded. This allows for news broadcasts, sound clips, and other streaming audio and video data to be played live from the Internet. Thanks to real-time processing, people can access information without having to wait for it. This is an important benefit since these days, anything that takes longer than 5 seconds seems like a long time.
Updated: January 8, 2007
WebSockets allow real-time communication between the Mobile App and the Server. You will learn the principles through a concrete example of a basic real-time multiplayers game.
Difficulty: Intermediate
Forewords
Unless you are building an application that does not need to exchange information with a server, communication between a Mobile Application and a Server is a must.
HTTP Client Server
Communication between a Mobile Application and a Server is usually achieved through the HTTP protocol, where the client (= mobile app) sends a HTTP request to a Server over the Internet. Once the Server has processed the request, it returns the answer back to the client and closes the connection.
This is a one-way direction communication, where the communication must always be initiated by the client and consists in a single exchange (send -> receive -> close). The server has no possibility to send anything to the client without having been asked, by the client, to do so.
Most of the time, this means of communication is enough and even recommended. However, if you need to poll the server very frequently, move high-volume of data, react based on events that could occur at the server-side, this way of communication might become a bottleneck.
WebSockets
Some other types of applications such as chat, real-time games, auctions… may require to:
have a communication channel that remains open between the client and the server for a longer period than a single request/response scheme
have a bi-directional data transmission, where the server could send data to the client without having been requested/polled by the client
support data streaming
WebSockets allow the client-side to open and persist a connection to the server.
A Web socket is a TCP socket connection between the client and the server, over the network, which allows full duplex communication, in other words: data can be transmitted in both directions and at the same time.A TCP socket is an endpoint instance, defined by an IP address and a port.
For a fully detailed documentation on the technical side of the WebSockets, please refer to RFC6455.
WebSockets in Flutter
The web_socket_channel package provides wrappers for WebSocket connections.
To install this package, add the following line to your pubspec.yaml file:
To import the package, add the following 2 imports to your .dart files:
How to connect to the Server?
To connect to the Server, you at least need to know:
its TCP socket address (e.g. 192.168.1.25:1234)
the name of its web sockets handler (e.g. “/svc/websockets”)
the URL scheme (‘ws://’ for plain-text communication or ‘wss://’ for an encrypted channel)
Under the hood
This simple line sends a regular HTTP request to the Server, which also contains an “Upgrade” header to inform the Server that the client wishes to establish a WebSocket connection. This request initiates the “handshake” process.If the Server supports the WebSocket protocol, it agrees to upgrade and communicates this through an “Upgrade” header in the response. Once the handshake is complete the initial HTTP connection is replaced by a WebSocket connection that uses the same underlying TCP/IP connection.
The Channel is now open and ready to be used.
Is it safe?
Well, if you only rely on the base protocol “ws://', it is as safe as the normal “http://” protocol.
Therefore, it is strongly advised to use the same encryption as for HTTPS (TLS/SSL).
To establish such secured communication, you need:
a SSL certificate installed on your server
use “wss://” rather than ‘ws://’
point to the SSL port
Extend the security by authenticating the client
As described in a previous article, you could also use the notion of “tokens', and only allow authenticated clients to connect.
Therefore, you could also pass some extra data to the header during the connection.
The following example illustrates how to pass extra data in the request header.
How to close the communication?
The communication channel may be closed by the client, using the following command:
How to send messages to the server?
How to handle communication from the server?
To be able to accept incoming messages issued by the Server, you need to subscribe (listen) to events from the Stream.
The signature is the following:
where:
onData: method which is invoked when some data is received from the Server
onError: method to handle any errors
onDone: method to implement to handle a communication closure (from the Server, for example)
cancelOnError: (default false). If set to true, the StreamSubscription is automatically closed at first error event
So, a typical implementation would be:
Let’s put all this in practice
Unlike most of the samples you may find on Internet, I am not rewriting the usual Chat application to explain this topic.Instead we are going to build the skeleton of a real-time multiplayers game. Something like a Tic-Tac-Toe game.
The example will consist in:
A Websockets server, written in NodeJS
A Mobile App Game where:
Users will provide their name to join the Game;
The list of all players will be refreshed in real-time;
One User will select another player to start a new game;
Both players will be simulateneously notified an brought to the Tic-Tac-Toe board game;
Players will have the possibility to:
Resign;
Play and their moves will be directly visible on the other player board.
Disclaimer
This sample is only aimed at illustrating the topic. The game skeleton we are going to write is very basic, not complete and subject to huge amount of improvements, validations…
The High-Level view
At first, we need to describe the game from both client and server sides.
Client-Side
The client-side (the Mobile App itself), will consist in 2 screens.
Screen 1:
This screen will allow the user to:
Enter a player name and join the game (= action: “join')
See the list of all players who joined the game (= action: “players_list')
Select a player and start a new game (= action: “new_game')Both players will then be automatically brought to the second screen.
Screen 2:
This screen will display:
The name of the opponent player
A resign button. If the user taps this button, the player resigns the game (= action: “resign').Both players are then brought back to the Screen 1
A Tic-Tac-Toe grid, made up of 9 cells.
When a player clicks on a cell of the grid, the player symbol (“X” or “O”) will be displayed on both players’ Mobile App
Server-Side
The server-side will only:
Record the list of all players and give the players with a unique ID
Broadcast that list to all players when a new player joins
Record the players of new games
Convey one player’s actions to the other game player
Communication Protocol
Real Time Strategy Games Pc
In order to have communication between the players and server, we need to define some kind of language. We are calling this “protocol'.
All messages that will be sent to the server or from the server to the Mobile App will follow this protocol, which consists in:
an action
some data
For convenience, I will use the following JSON object (= Map):
The following diagram shows the protocol:
The Server-side: WebSocket server
For this very basic WebSocket server, I opted for an implementation in NodeJS, using the “WebSocket” package.
to have NodeJS (version > 6) installed (refer to NodeJS Website for further details on installing NodeJS).
install the “websocket” packageuse “npm install websocket –save” to install the package
The Source Code
The source code is this WebSocket server is very basic. Let’s first have a look at it, explanation goes along with the code.
The Client-Side: Mobile App
Now that we have the server, let’s consider the Flutter application.
The Websocket Helper
Let’s start by implementing the WebSocket Helper class.
Real Time Games Online
This class is a Singleton that handles the communication based on WebSockets.
I implemented it as a Singleton in order to allow its reuse across the whole application without having to care about the connection.The simple fact of importing this .dart file, is enough to use the socket (application-level global variable).
The Game Communication Helper Class
This class is responsible for handling the websockets communication related to the game.This class is also implemented as a Singleton since it will be used by the 2 screens.
Why did I choose to implement a Game Communication Helper on top of the WebSockets Helper?
Simply because, all the logic related to the Game is centralized. Also, because if we would like to extend the game by adding some Chat feature, for example, we would only have to create a specific class which would also rely on the same WebSockets Helper.
Screen 1: Where the user joins and launches a new game
This screen is responsible for:
Letting the user join the game, providing a name
Maintaining a real-time list of all the players
Letting the user start a new game with another player
Screen 2: the Game Board
This second screen is reponsible for:
displaying the name of the opponent in the AppBar
allowing the user to resign, via a ‘Resign’ button
displaying the game, real-time, together with all the moves
allowing the user to play a move and send the move to the opponent.
The main
Finally, we have the main routine that simply launches the first screen.
The results
Real Time Strategy Games Online
Sir mix a lot interview. The following video shows 2 mobile devices running this sample application.As you may see, interactions are real-time.
Conclusions
WebSockets are easy to implement and are essential when a Mobile App needs to deal with real-time and full-duplex communication.
I hope that this article demystified the concept of WebSockets through this practical example, which, once again, is only aimed at demonstrating the communication using WebSockets.