PeerGaming – Share the Fun
Creating a Client-Side Multiplayer Gaming Framework for the Web,
which handles Distributed Logic on Multiple Systems in “Real-Time”
Bachelor Thesis
Stefan Dühring
April - July 2013
Hochschule für Technik und Wirtschaft Berlin (HTW)
International Media and Computing (IMI)
Student No.: s0531721
Supervisors
Prof. Dr. Christin Schmidt (AI)
Prof. Dr. David Strippgen (IMI)
Abstract
Creating a multiplayer game or implementing a mode for various players can be quite
challenging. In addition to the original client, developers need to take care of the backend as
well and deal with additional hard- and software requirements. A persistent infrastructure has
to be setup to provide a layer for communication and synchronization between the different
systems.
PeerGaming is a client-side multiplayer gaming framework for the web, which helps you to
solve some of these problems and connect multiple browsers directly using WebRTC.
It establishes connections, creates channels and provides a simple interface to ease the
process of creating your own game.
As a game developer, you shouldn't be struggling with handling network issues anymore!
Dedication
In remembrance to all connections which don't exist.
This document is available under the creative common license (CC BCY 3.0).
Its created at the HTW Berlin and got public released on the 25
th
July 2013.
An online version can be found at thesis.peergaming.net.
Table of Contents
1 Introduction........................................................................................................................................1
1.1 Background...................................................................................................................................1
1.2 Problem.........................................................................................................................................2
1.4 Structure........................................................................................................................................4
2 Foundations........................................................................................................................................5
2.1 Games............................................................................................................................................5
2.2 Networks.......................................................................................................................................7
2.2.1 Architectures............................................................................................................................7
2.2.2 Topologies................................................................................................................................8
2.3 Web Technologies........................................................................................................................10
2.3.1 Browser..................................................................................................................................10
2.3.2 Standards................................................................................................................................11
2.3.3 JavaScript...............................................................................................................................12
2.4 WebRTC......................................................................................................................................13
2.4.1 API.........................................................................................................................................13
2.4.2 Protocols................................................................................................................................14
2.4.3 Connection.............................................................................................................................16
3 Analysis.............................................................................................................................................19
3.1 Market.........................................................................................................................................19
3.1.1 Plugins...................................................................................................................................19
3.1.2 Services..................................................................................................................................21
3.1.3 Frameworks...........................................................................................................................23
3.2 Vision...........................................................................................................................................25
3.3 Requirements...............................................................................................................................26
4 Design................................................................................................................................................27
4.1 Principles.....................................................................................................................................27
4.2 Workflow.....................................................................................................................................28
4.2.1 User........................................................................................................................................28
4.2.2 Developer...............................................................................................................................29
4.3 Network Topology.......................................................................................................................31
4.4 Design Patterns............................................................................................................................32
5 Implementation................................................................................................................................33
5.1 Server...........................................................................................................................................33
5.2 Client...........................................................................................................................................35
5.2.1 Rooms....................................................................................................................................37
5.2.2 Users......................................................................................................................................39
5.2.3 PeerChain...............................................................................................................................41
5.2.4 Initialization...........................................................................................................................42
5.2.4 Services..................................................................................................................................44
5.2.5 Reactive.................................................................................................................................46
5.2.6 Backup...................................................................................................................................47
5.2.7 Synchronized.........................................................................................................................48
5.3 Challenges...................................................................................................................................51
5.3.1 Debugging.............................................................................................................................51
5.3.2 Race Conditions.....................................................................................................................52
5.3.3 Interoperability......................................................................................................................53
6 Conclusion.........................................................................................................................................54
6.1 Evaluation....................................................................................................................................54
6.2 Reflection....................................................................................................................................55
6.3 Future...........................................................................................................................................56
7 Appendix...........................................................................................................................................57
8 Glossary.............................................................................................................................................62
9 Sources..............................................................................................................................................66
Table of Figures
Figure 1: Full Connected Network.............................................................................................................8
Figure 2: Star Network...............................................................................................................................9
Figure 3: Ring Network.............................................................................................................................9
Figure 4: Tree Network..............................................................................................................................9
Figure 5: WebRTC protocol layers...........................................................................................................16
Figure 6: JSEP / ICE – retrieving the public IP address..........................................................................17
Figure 7: JSEP / ICE - exchange candidates & SDP container................................................................18
Figure 8: JSEP / ICE - established a connection to another peer.............................................................19
Figure 9: Steps of user interaction...........................................................................................................29
Figure 10: Data types in multiplayer games............................................................................................31
Figure 11: result of a survey about the interest in multiplayer games, created by Google Docs.............32
Figure 12: Game initialization by following the peerchain (setup).........................................................44
Figure 13: Synchronization - set local cache and request remote value..................................................49
Figure 14: Synchronization - return remote value for confirmation........................................................50
Figure 15: Synchronization - set value and invalidate caches.................................................................51
If no additional information are provided, the graphics are created by the author and based on
their according context.
Page 1
1 Introduction
The following will provide some insight about the current situation of connectivity and
introduce the problem I like to solve in the thesis.
1.1 Background
For the first time in history were more smartphones sold than feature phones in Q1 2013.
According to a study grow the market about 43% compared to the previous year.
1
There are several reasons for the ongoing interest – whether it be the basic idea of accessing
the internet at any time via a mobile connection or using new features provided by the latest
technologies. Undoubtedly one of the most important aspects are the mobile applications
and additional functionalities that come along with them. Aside from direct communication
is playing games one of the major use cases on these devices.
Traditional entertainment system, such as mobile handhelds like the Nintendo DS, the
Playstation Portable or even home consoles like the XBOX, have therefore to compete with
these phones and tables.
As handsets are replacing these specific systems more and more, the vendors are following
the trend and extend their systems with missing features to improved their web capabilities.
While the NDS was the first commercial successful console which got a browser as a default
system application, the Nintendo WiiU even offers a Web Framework to create games and
promotes them as first class citizen on their distribution channels.
2
As developing software for different platforms with a specific SDK or programming language
often requires more time and additional funding than a cross-browser web application,
the interest in rich internet applications like browser based games is increasing.
3
1 http://www.idc.com/getdoc.jsp?containerId=prUS24085413
2 https://wiiu-developers.nintendo.com/
3 http://readwrite.com/2012/06/05/5-ways-to-tell-which-programming-lanugages-are-most-popular
1 Introduction
Page 2
1.2 Problem
The best way to reach a large audience is releasing a product on multiple distribution
channels. Referred to video games, this can lead to creating a multiplayer game
in the browser – to attract a variety of players and keep the porting costs as low as possible.
After I did some research (see 1.3 Methodology), I found different approaches for the
development of a game in a browser. Unfortunately none of these were simple or really
appropriated towards the game design. Previous projects I worked on were mainly story
driven and just for a single player, so I have limited knowledge about networking and
hoped for a best practice guidance which allows immediate feedback via rapid-prototyping.
In the end I had to setup a network infrastructure, get a server and maintain the it's code in
another programming language. During the development I recognized that their will be similar
tasks required for each kind of real-time multiplayer game, disregarding its actual content.
To prevent repetition and help other developers who are perhaps struggling with a similar
problem I decided to create a client-side multiplayer gaming framework for the web, which
handles distributed logic on multiple system in “real-time”.
1 Introduction
Page 3
1.3 Methodology
Without prior knowledge about multiplayer games in a browser or networks, I decided to pick
a few examples and examine on which technology they are based and how they got created.
Smaller browser based games are often available on specific portals, while larger titles are
available on their specific domain. Noteworthy games I found were Runescape
4
, Canabalt
5
,
PolyCraft
6
, BrowserQuest
7
and HexGL
8
.
Although some of them are commercial licensed and others are open source, they provided
a good overview about the environments and programming languages which can be used
in a browser. It ranges from proprietary plugins up to standard web technologies.
The multiplayer aspect is also realized in different ways as well. While some are directly
participating at the same game session, others use an indirect approach and strife for a new
highscore. This can either be done synchronous (turn-based waiting for the input of others)
or asynchronous in real-time without slowing down the actions.
A detailed analysis about the different tools for the creation can be found in “3. Analysis”.
4 http://www.runescape.com/
5 http://adamatomic.com/canabalt/
6 http://polycraftgame.com/
7 http://browserquest.mozilla.org/
8 http://hexgl.bkcore.com/
1 Introduction
Page 4
1.4 Structure
At first I will explain more about the current state and provide an overview about the essential
topics: games, networks and their usage at multiplayer games in a browser. Afterwards I will
present existing solutions and point out the difference towards my idea.
In the main part, I will summarize the basic concepts of the framework which influenced the
actual implementation. This will be described by following the different steps which are done
by users and developers. Aside from the usage, the core features and challenges of the
development will afterwards be mentioned - just before the project will be evaluated at the
end. With a reflection about the expectations, limitations and plans for upcoming versions I
will complete the thesis.
You can find the source code of the framework on the enclosed CD, along with some
additional material for the project. Since the whole projects is based on the idea of open
knowledge and free culture, the latest version is also available online. Further details about
the setup can be found in the attached guide.
1 Introduction
Page 5
2 Foundations
During the research I learned more about certain topics, which I like to explain in advance.
It should provide a basic understanding of the terms and common usages of patterns.
Specific abbreviations can be found in “8. Glossary”.
2.1 Games
There are various descriptions about “games” and “play”, but none of them can be used as
an absolute definition. A reason are the perspectives, from which specific point of view the
aspects are regarded. The different cultures also influenced the idea of games, for instance
by promoting public events or reserving terms of the language.
Games can be divided in to different kind of categories. The groups are defined by similarities
and reused patterns either by their medium, the actual content or the amount of players
participating. As games can offer alternative modes – they can be found in multiple sections.
The most simple classification of a game is judged on the material: is it analog or digital.
Many traditional analog boardgames were later on also ported as digital video games.
Regarding to video games, they can also be classified by their specific platform they got
released. Aside from consoles, computers or mobiles, browser defines nowadays their own
category. Although their running on top of different kind of systems, games distributed over
the internet and directly accessible are called browser based games.
Another filing can be done by the core mechanics used in a game. Independent from their
physical or virtual existence, each game can focus on qualifications like luck, fitness, strategy,
tactics or knowledge. Video games will also add sub-genres like Real Time Strategy,
First Person Shooter or Role Playing Game to be more specific in terms of their gameplay
and environment.
2 Foundations
Page 6
The level of difficulty and the targeted audience can also be a factor. Casual gamers prefer
simplicity with a short introduction, while core gamers or professionals are more interested in
the depth instead of the shallow experience.
Social components can also be a criteria: in opposite to a single user, games with multiple
participants can be defined as multiplayer games. The interaction between those players and
game elements can again be either competitive or cooperative.
The framework and thesis itself will focus on the technical aspects of a multiplayer game,
which can be any kind of genre, setting or style.
2 Foundations
Page 7
2.2 Networks
Computer networks are the backbone of our modern society, as they allow accessing data
from remote systems and communication in real-time with other people.
Although true “real-time” barely exist from a technical point of view – its often used to describe
a signal transport without noticeable delay. A high bandwidth connection and low network
latency will create such perception.
2.2.1 Architectures
Networks use digital or physical transports to connect multiple systems with each other.
The infrastructure can be defined by different criteria, for instance the instruction types
and data-streams internally used. A more common approach is the classification by the
communication roles of the systems in the application network.
On the one hand is a client, which opens a socket to create a connection to another system.
The machine which listens to this incoming connections is called a server. Their relation and
functionalities keeps the same during the runtime. A multi-tier design uses the client-server
architecture with a strict hierarchy by declaring the roles for each layer independent.
In contrast to the classical client-server model, a system which is able to change its role or act
as both can be described as a peer. It can create connections and listen to them regarding
their current state and implementation even at the same time.
Both kind of systems are used nowadays and depending on the features of the application,
specifically designed with the benefits and disadvantages in mind. Reliability, accessibility,
maintainability, security, latency and costs are a few factors for measurement.
2 Foundations
Page 8
While the client-server architecture provides a central host for transferring and storing data,
its also a single point of failure in the infrastructure. The network is limited by the resources
the computer provides. Even if a switch is used to balance the traffic by addressing multiple
servers instead of one, there is a restriction on scalability how many concurrent clients can be
connected and handled.
Peer-to-peer system have to take care of the opposite: as no central location is available to
send or retrieve information, the peers don't know which other peers are online and available.
The initial connection is more complex and requires heuristic data or an additional service for
bootstrapping. Without a permanent host persistent data can also not reliable stored on a
single system.
2.2.2 Topologies
Aside of the roles or technical components - a network can use different kind of structures
to organize the communication inside. The connections of the nodes (server, client or peer)
defines the flow and efficiency in handling data. Similar to architectures, depends the topology
on the specific needs of the application. As peer-to-peer systems are more flexible in their
organization, the design is significant for the result. Common topologies are:
Fully Connected Network
Every peer is connected with each other peer in the network.
+ direct connections / short distance without a proxy
- doesn't scale well (resource management of 1:n
connections)
Figure 1: Full Connected Network
2 Foundations
*
* https://github.com/Raynos/topology , 23.07.2013 - 11am
Page 9
Star Network
Every peer is connected to one peer, which manages the data
communication as a central hub.
+ peers just handle 1:1 connection, simple to add new nodes
- dependency on the central peer (see client-server)
Ring Network
Each peer is connected with two others, defining a closed loop.
+ always 1:2 connections
- multiple points-of failure, slow transfer over long distances
Tree Network
Each peer takes a position in a hierarchy and is either a root
node with childs or a “leaf” of one.
+ support subnets on disruption
- requires a defined hierarchy matching
Figure 2: Star Network
Figure 4: Tree Network
Figure 3: Ring Network
2 Foundations
Page 10
2.3 Web Technologies
Nowadays is the internet the largest global network world wide which connects many
smaller networks and systems. The “web” describes a system defined by links between
different documents and provide an accessible infrastructure for various services on top.
2.3.1 Browser
A browser is an application which enables the user to visit websites by following the route of
referred documents. While previous version were purely based on text and ASCII encoding,
modern variants include even audio and video support.
There are currently 5 browser vendors at the time which cover the majority of internet users:
Mozilla Firefox, Google Chrome, Apple Safari, Microsoft Internet Explorer, Operas Opera.
With the growing interest in the mobile market, they also provide mobile variants of their
browsers on the specific platforms along the desktop.
Compared to other platforms the web suffers especially from outdated software. Developers
just create a part of the experience, since the browser is the real client which renders the site
or executes the logic of an application. The capabilities and usable features are therefore
defined by the systems the visitors are running.
So even though its easier to access web content, compared to a native” application on a
device where an additional installation is necessary for the start, it's limited by the sandbox its
running in. The inconsistency of the different browsers implementations, as well as unknown
hardware requirements needs to be considered by web developers.
2 Foundations
Page 11
2.3.2 Standards
In addition to the general infrastructure, a common aspect of the web as a platform are the
different standards on which users, developers and vendors can rely on. These include
recommendations by organizations like the W3C, the IETF and Ecma International.
9
Although it was originally just designed for simple documents, the web nowadays consists of
different components including visual elements, multimedia streams, dynamic text content
and interactive applications. Standard web technologies include HTML for the content,
XML as a structure and CSS for the styling.
During the last decade, the idea of running real applications directly in the browser got
promoted. Shifting heavy computation towards the client and extending the possibilities,
allows to create thick clients and leverage the server resources.
9 http://www.webstandards.org/learn/faq/#p2
2 Foundations
Page 12
2.3.3 JavaScript
JavaScript is a dynamically typed, object based, interpreted programming language.
It was originally created to run in browsers to extend their functionality, but can also
be used in different environments which are using scripts.
The current version of the language is 1.8.5 and based on the ECMAScript 5 specifications
from 2011 defined in ECMA-262
10
. Its written and proposed by the Technical Committee 39
(TC39), including members from the major browser vendors and technical experts.
Although it doesn't belong to the official W3C standards, JavaScript is as a part of the
standard web technologies. While HTML is static and represents the content, JavaScript
can be used in conjunction with the DOM to add behavior and interactions. Creating new
Elements, adding inline styles, changing the text or requesting information is possible by
using the API provided by the browsers.
The language itself got created in 10 days
11
and because of the dependency on a browser,
it had to be defined with backwards compatibility for older versions in mind. Therefore it
uses prototypical inheritance for extensibility.
It also promotes functions as first class citizens, which allows to simply adapt towards the
nature of functional programming and write expressive code. In addition it got short literals for
objects, arrays, numbers, strings and regular expressions.
12
The term “HTML5” is frequently used as a buzzword for modern web technologies, which can
be used with JavaScript. Despite its origin as the fifth revision of the HTML standard,
new browser APIs and CSS3 properties are commonly referenced as well.
10 http://www.ecma-international.org/publications/standards/Ecma-262.htm
11 http://www.computer.org/csdl/mags/co/2012/02/mco2012020007.html
12 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Literals
2 Foundations
Page 13
2.4 WebRTC
WebRTC is the shorthand forWeb Real-Time Communication”, a set of new JavaScript APIs
for the browser – which allow real time communication. It is defined by groups of the
W3C (WebRTC) and the IETF (RTCWeb).
Google acquired Global IP Solution (GIPS) in May 2010 and obtained with them technologies
for real-time voice and video encoding. They provided them royalty free and proposed a
JavaScript API to use them directly in the browser. Together with Mozilla, Opera and guidance
by CISCO and Ericsson they promoted the draft. Meanwhile Microsoft works on its own
specification CU-RTC-WEB, regarding a different implementation of the used technologies.
13
2.4.1 API
Currently the API is still in the editorial process and yet not a full recommendation for the
browsers. The WebRTC specification
14
consists mainly of 3 components:
PeerConnections can establish a direct connection between two clients
MediaStreams
15
allows to retrieve continuous signals from input sensors
DataChannels are able to send and receive arbitrary data across a peerconnection
As the APIs to access these parts are not final and still changing, not all browser support
every feature. The best coverage have MediaStreams, which can be accessed by a prefixed
version of “navigator.getUserMedia()”.
13 http://html5labs.interoperabilitybridges.com/prototypes/cu-rtc-web/cu-rtc-web/info
14 http://dev.w3.org/2011/webrtc/editor/webrtc.html
15 http://dev.w3.org/2011/webrtc/editor/getusermedia.html
2 Foundations
Page 14
A permission request will prompt to the users and after acceptance, provide a mediastream
object which can either be used on the local system or send to a remote computer by
attaching it to a PeerConnection. Aside from the majority of desktop browsers, even some
mobile variants support camera records.
The implementation of PeerConnections and DataChannels on the other hand just recently
shipped into the stable versions of the browsers. Currently only Firefox 23+ and Chrome 27+
support DataChannels and because of their different implementations, communication using
DataChannels for text based messages is unfortunately not interoperable between them.
The setup and underlying protocols for using PeerConnections are described in the following.
2.4.2 Protocols
Different kind of protocols can be used as the transport layer to transfer data over a network.
The most well know protocols for the internet are the Transmission Control Protocol (TCP)
and the User Datagram Protocol (UDP).
TCP creates a reliable connection between two systems. It automatically split up large
messages, streams these data in chunks and re-assembles them on the other side to the
original. Through the process it takes care of the package orders and guarantees the arrival.
On the other hand is UDP purely based on packets. It sends messages to a multicast group,
on which every participant will receive the data. In contrast to TCP it doesn't provide extensive
features like the conversion in smaller segments and the flow control to ensure the order. The
error correction by the streaming interface is also missing so part of the input can be
corrupted or even lost during the transport.
While TCP is commonly used for 1:1 requests like in a browser to ensure the result,
UDP transfers got the advantage of having a low latency and therefore are commonly used
2 Foundations
Page 15
at real-time communication. Since UDP doesn't provide an interface which handles the data,
there is no additional overhead compared to a TCP stream. Therefore application which are
updated frequently like media streams and games (were the loss of the previous package is
not critical considering the fast delivery of the next frame) prefer the usage of UDP.
PeerConnections are using UDP for the transport and different application layers on top.
By default the basic Real-time Transport Protocol (RTP) is used for handling messages.
As a MediaStream will be attached to a PeerConnection, the signals will be encrypted
and use the Secure Real-Time Transport Protocol (SRTP).
Data send via a DataChannel will use the Datagram Transport Layer Security (DTLS).
An upcoming version will also include the opportunity to enable a reliable DataChannel
based on the Stream Control Transmission Protocol (SCTP), which provides a similar
congestion control like TCP – but will be run over UDP.
Figure 5: WebRTC protocol layers
2 Foundations
Page 16
2.4.3 Connection
WebRTC is implemented by following the JavaScript Session Establishment Protocol (JSEP),
which defines an interface to control the Interactive Connectivity Establishment (ICE)
framework from within the browser using a JavaScript API. It allows to create a direct
connection between two systems which are behind network address translators (NATs).
The problem is that most computers will only know about their private IP on the internal
network, but not their public address. In order to contact another system over the internet
directly, it needs to obtain the public address of the partner.
The first step of the ICE implementation in the browsers is to specify the address of a server,
which provides support for Session Traversal Utilities for NAT (STUN). A server using the
STUN protocol will simply send the public IP back to the client, so it knows about its own
address on the internet. In some cases can the public address not be resolved, as fore
instance a strict firewall prevents accessing the information. Even though this happens to just
1 system out of 7
16
, a fallback needs to be provided to still work properly. Therefore the URL
of a Traversal Using Relays around NAT (TURN) server should added as well. If the previous
request towards a STUN server fails to return the address, it will connect to a TURN server
which will then be used as a relay for all transmitted data over the connection.
16 http://io13webrtc.appspot.com/#51
Figure 6: JSEP / ICE – retrieving the public IP address
2 Foundations