SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
More Than Just WebSockets for
Real-Time Multiplayer Games and
Collaboration
Alessandro Alinone
CTO, Lightstreamer
HTML5 Dev Conf
San Francisco / 2013-10-22
Cool, I bet you have already played with them.
With WS you unleash the power of real-time
bi-directional communication in the browser.
But WS are just a transport layer, which makes
it extremely easy to clutter the network.
WS might not be enough to make your new
HTML5-amazingly-real-time app take off...
WebSockets?
You need a full stack of abstractions over WS,
to:
1. Optimize the traffic (reduce bandwidth
and latency)
2. Simplify code development and increase
code robustness, by using higher-level
constructs and paradigms
So, what?
Can we reuse the mechanisms originated for
financial trading apps and apply them to
HTML5 gaming and collaboration?
You bet!
Idea
Now please go to:
bit.ly/mor888
Interactive room with char-by-char chat.
Fully real-time movements in the room.
Check out the game loop...
onItemUpdate: function(upd) {
var x = upd.getValue("posX");
if (x !== null) {
this.avatar.style.left = (x-(this.avatar.offsetWidth/2))+"px";
this.posX = x;
}
var y = upd.getValue("posY")
if (y !== null) {
this.avatar.style.top = (y-(this.avatar.offsetHeight/2))+"px";
this.posY = y;
}
}
Even if the physics of interaction among many objects is
pretty complex, the client simply has to move some divs
to the given coordinates (full offloading of the physics to
the server).
Multiplayer Games: Pure Server-side Mode
Positions
Commands
Positions
● Physics runs on server side only
● Stream of user commands from clients to server
● Broadcast of position updates from server to clients
● Clients are pure renderer, with no prediction and no
interpolation
Real-Time
Server
Client
(HTML5 Browser)Commands
Client
(HTML5 Browser)
Client
(HTML5 Browser)
Positions
Commands
Commands = user input
(key press, joystick move,
device tilt, accelerometer,
etc.)
Positions = current position
of each object (coordinates,
quaternions, etc.)
sim
plified
view
Others'Commands
Commands
Others'Commands
● Physics runs on the client side only
● Stream of user commands from clients to server
● Broadcast of all users' commands from server to clients
● Each client calculates the world independently
Real-Time
Server
Client
(HTML5 Browser)Commands
Client
(HTML5 Browser)
Client
(HTML5 Browser)
Others'Commands
Commands
Commands = user input
(key press, joystick move,
device tilt, accelerometer,
etc.)
Others' Commands =
commands originated from
all other players
sim
plified
view
Multiplayer Games: Pure Client-side Mode
Multiplayer Games: Hybrid Mode
Others'Commands
Commands
Others'Commands
● Physics runs on both server and client side
● Stream of user commands from clients to server
● Broadcast of all users' commands from server to clients
● Periodic broadcast of position updates from server to cl.
● Each client calculates the world and resyncs with
authoritative server
Real-Time
Server
Client
(HTML5 Browser)
Commands Client
(HTML5 Browser)
Client
(HTML5 Browser)
Others'Commands
Commands
Commands = user input
(key press, joystick move,
device tilt, accelerometer,
etc.)
Others' Commands =
commands originated from
all other players
Low-Freq Positions =
periodic updates of object
positions
sim
plified
view
Low-freqPositions
Low-freqPositions
Low-freqPositions
Pure server-side mode
Cons: potentially high bandwidth; animations subjected to
network latency and congestion
Pros: much simpler client code; cheaper client hardware
Pure client-side mode
Cons: worlds can diverge; complexity to align initial state
Pros: smoother and more reactive animations
Hybrid mode
Cons: more complex to implement
Pros: the best of two modes; client prediction and
interpolation can be used
Pros of TCP:
● Reliable (in-order guaranteed delivery)
● If Web protocols are used, can pass through proxies
and firewalls
Cons of TCP:
● Retransmissions... If a segment is lost, newer data
queues up in the server buffers until the initial
segment is actually delivered. This provokes a clutter
on the network, as bursts of aged data are sent out,
with the risk of triggering a continuous packet loss on
small-bandwidth networks.
TCP vs. UDP
A high-frequency stream of real-time data can be handled
by a streaming server via queuing or resampling.
In many cases, not all the data samples are needed. With
resampling, the amount of data is reduced. Receiving less
frequent updates does not mean receiving old updates.
Resampling a real-time data flow is a procedure that
needs to take several variables as input:
● unsampled data flow
● desired maximum frequency
● desired maximum bandwidth
● currently available bandwidth
Data Resampling
● Bandwidth allocation: For each client, max bandwidth
allocated to its multiplexed stream connection.
Allocation can be changed on the fly.
● Frequency allocation: For each data flow of each
client's multiplexed stream connection, max update
rate can be allocated. Allocation can be changed on
the fly.
● Real bandwidth detection: Internet congestions are
detected and the server continuously adapt to the
currently available bandwidth.
The streaming server should heuristically combine these
three categories of information to dynamically throttle
the data flow applying resampling.
Dynamic Throttling
Instead of simply discarding updates, when resampling is
done, the sender should try to merge them to save as
much information as possible.
Example:
Event 1: X=5.1; Y=3.0; Z=2.3
Event 2: X=unchanged; Y=3.1; Z=2.5
Event 3: X=5.3; Y=unchanged; Z=2.8
If the resampling algorithms decides to drop event 2, the conflation
mechanism will produce a single update, merging 2 and 3:
Conflated event (2-3): X=5.3; Y=3.1; Z=2.8
Conflation
Disable Nagle's algorithm (TCP_NODELAY).
Pack updates efficiently into TCP segments.
What is the maximum latency you can accept to forge
bigger TCP segments and decrease the overheads (both
network overheads and CPU overheads)?
The highest the acceptable latency, the more data can be
stuffed into the same TCP segment (batching), increasing
overall performance.
Batching
Now please go to:
bit.ly/mor777
(better with Chrome)
We took the HTML5 version on Super Mario Bros. and
made it multiplayer in a few hours... (it's not perfect, but
gives an idea).
Thanks to Josh Goldberg for creating the HTML5 version of Mario!
triggers.js
function keydown(event) {
...
lsSendUserUpdate(event, 0); // Send key press event to Lightstreamer
}
function keyup(event) {
...
lsSendUserUpdate(event, 1); // Send key press event to Lightstreamer
}
function lsSendUserUpdate(key, upOrDown) {
lsClient.sendMessage(key + "|" + upOrDown + "|" + mario.left + "|" +
mario.top + "|" + mario.power + "|" + gamescreen.left + "|" +
gamescreen.top + "|" + currentmap[0] + "|" + currentmap[1] + "|"
+ area.setting, userGuid);
}
Sending local Mario's commands to the server
(and piggybacking positions to correct drifts)
Receiving remote Marios' commands from the server
maps.js
lsSubscription.addListener({
onItemUpdate: function(updateInfo) {
try {
var user = updateInfo.getValue("key");
var status = updateInfo.getValue("command");
switch (status) {
case "ADD":
lsProcessAddUser(user); break;
case "DELETE":
lsProcessDeleteUser(user); break;
case "UPDATE":
lsProcessUpdateUser(user, updateInfo); break;
}
} catch (e) { log(e); }
}
});
maps.js
function lsProcessUpdateUser(user, updateInfo) {
...
var mario = window.otherMarios[user];
...
setLeft(mario, updateInfo.getValue("xLoc") + ...);
setLeft(mario, updateInfo.getValue("yLoc") + ...);
...
var involvedKey = parseInt(updateInfo.getValue("involvedKey"));
var upOrDown = parseInt(updateInfo.getValue("upOrDown"));
switch (upOrDown) {
case 0:
handleKeyDownUpdate(mario, involvedKey); break;
case 1:
handleKeyUpUpdate(mario, involvedKey); break;
}
Managing remote Marios' commands
(together with piggybacked positions to correct drifts)
Delta Delivery
Lightweight Messages
Instead of sending a full world snapshot at each update,
send only the actual changes (delta) since the last update.
Full snapshots are sent only at client startup and after
disconnections.
Avoid verbose data representations such as XML and
JSON, which carry redundant metadata (field names) with
each update.
Go for lightweight representations, such as position
based, to reduce message size.
Automatic Detection of Best Transport
There are still many cases in the real world where
WebSockets are blocked by network intermediaries.
Automatic and fast fall-back on a per-connection basis, to
reach all clients.
WebSocket
HTTP Streaming
HTTP Smart Polling
WebSocket
HTTP Streaming
Contrary to common belief, the real advantage of WS over
HTTP Streaming is in client-to-server messaging.
Implement ordering, acknowledge, retransmissions, and
baching even over HTTP, to reach all clients.
Client-to-server In-order Guaranteed
Message Delivery
ServerBrowser ServerBrowser ServerBrowser
TCP connection 1 TCP connection 1 TCP connection 2
WebSocket
HTTP
Now please go to:
bit.ly/mor345
You need a publish-subscribe paradigm to govern which
messages should be delivered to which clients.
With asymmetric pub-sub, the subscribers are on the
client side and the publishers are on the server-side.
Clients send messages to the publishers, which use them
to create the actual messages to publish.
Message Routing
Data Adapter Client
Publisher Subscriber
sendMessage
Subscriptions should be based on items and schemas
(sets of fields)
Item: object5 - Fields: "posX", "posY", "posZ", "rotX", "rotY", "rotZ", "rotW"
Every client can subscribe to as many items it needs, each
with its own schema:
As a result, a multiplexed stream should be created:
Subscription Model
Client
subscribes
Field "A"
Item1
Field "B"
Field "C"
Field "X"
Item2
Field "Y"
Field "A"
Item3
Field "X"
Field "C"
Field "Y"
Clientdelivers Item 1
snapshot
Item 1
update 1
Item 2
snapshot
Item 1
update 2
Item 2
update 1
With the item-based approach, all the routing scenarios
can be supported: broadcast, multicast, and unicast.
Massive fan-out and individual messaging should be
supported on the top of the same physical connections.
Content-aware subscription modes can optimized data
based on their semantics.
Multiple Routing Scenarios
publishes
Item 1
publishes
Item 1
(once)
Data Adapter
Client 1,000,000
Client 1
... Massive fan-out,
broadcast
Data Adapter
Client 2
Client 1
publishes
Item 2
item 1
item 1
item 1
item 2
Personal messages,
unicast
Of course, your server needs to scale a lot to manage the
real-time data for massively multiplayer online games.
● Use a concurrent staged-event driven architecture
with non-blocking I/O.
● Automatically tune your thread pools based on the
number of CPU cores.
● Enable graceful degradation.
● Support horizontal scalability via clustering.
Results we got for a single server instance:
● One million clients, with a low message rate on each connection (a few
updates per minute per client).
● Tens of thousands clients, with tens of messages per second per client.
Scalability
Commercial time :)
Lightstreamer implements all the discussed techniques
and much more!
It's not open source, but free editions are available and we
have a Startup Program to help new entrepreneurs.
With 13 years of continuous evolution, it is the most
widespread solution in the finance industry, now
conquering several other verticals.
Links
Contact me
- alessandro.alinone@lightstreamer.com
- @alinone
Optimizing Multiplayer 3D Game Synchronization Over the Web
http://blog.lightstreamer.com/2013/10/optimizing-multiplayer-3d-game.html
3D World Demo
http://demos.lightstreamer.com/3DWorldDemo

Weitere ähnliche Inhalte

Kürzlich hochgeladen

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Kürzlich hochgeladen (20)

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

Empfohlen

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Empfohlen (20)

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 

More Than Just WebSockets for Real-Time Multiplayer Games and Collaboration

  • 1. More Than Just WebSockets for Real-Time Multiplayer Games and Collaboration Alessandro Alinone CTO, Lightstreamer HTML5 Dev Conf San Francisco / 2013-10-22
  • 2. Cool, I bet you have already played with them. With WS you unleash the power of real-time bi-directional communication in the browser. But WS are just a transport layer, which makes it extremely easy to clutter the network. WS might not be enough to make your new HTML5-amazingly-real-time app take off... WebSockets?
  • 3. You need a full stack of abstractions over WS, to: 1. Optimize the traffic (reduce bandwidth and latency) 2. Simplify code development and increase code robustness, by using higher-level constructs and paradigms So, what?
  • 4. Can we reuse the mechanisms originated for financial trading apps and apply them to HTML5 gaming and collaboration? You bet! Idea
  • 5. Now please go to: bit.ly/mor888
  • 6. Interactive room with char-by-char chat.
  • 8. Check out the game loop... onItemUpdate: function(upd) { var x = upd.getValue("posX"); if (x !== null) { this.avatar.style.left = (x-(this.avatar.offsetWidth/2))+"px"; this.posX = x; } var y = upd.getValue("posY") if (y !== null) { this.avatar.style.top = (y-(this.avatar.offsetHeight/2))+"px"; this.posY = y; } } Even if the physics of interaction among many objects is pretty complex, the client simply has to move some divs to the given coordinates (full offloading of the physics to the server).
  • 9. Multiplayer Games: Pure Server-side Mode Positions Commands Positions ● Physics runs on server side only ● Stream of user commands from clients to server ● Broadcast of position updates from server to clients ● Clients are pure renderer, with no prediction and no interpolation Real-Time Server Client (HTML5 Browser)Commands Client (HTML5 Browser) Client (HTML5 Browser) Positions Commands Commands = user input (key press, joystick move, device tilt, accelerometer, etc.) Positions = current position of each object (coordinates, quaternions, etc.) sim plified view
  • 10. Others'Commands Commands Others'Commands ● Physics runs on the client side only ● Stream of user commands from clients to server ● Broadcast of all users' commands from server to clients ● Each client calculates the world independently Real-Time Server Client (HTML5 Browser)Commands Client (HTML5 Browser) Client (HTML5 Browser) Others'Commands Commands Commands = user input (key press, joystick move, device tilt, accelerometer, etc.) Others' Commands = commands originated from all other players sim plified view Multiplayer Games: Pure Client-side Mode
  • 11. Multiplayer Games: Hybrid Mode Others'Commands Commands Others'Commands ● Physics runs on both server and client side ● Stream of user commands from clients to server ● Broadcast of all users' commands from server to clients ● Periodic broadcast of position updates from server to cl. ● Each client calculates the world and resyncs with authoritative server Real-Time Server Client (HTML5 Browser) Commands Client (HTML5 Browser) Client (HTML5 Browser) Others'Commands Commands Commands = user input (key press, joystick move, device tilt, accelerometer, etc.) Others' Commands = commands originated from all other players Low-Freq Positions = periodic updates of object positions sim plified view Low-freqPositions Low-freqPositions Low-freqPositions
  • 12. Pure server-side mode Cons: potentially high bandwidth; animations subjected to network latency and congestion Pros: much simpler client code; cheaper client hardware Pure client-side mode Cons: worlds can diverge; complexity to align initial state Pros: smoother and more reactive animations Hybrid mode Cons: more complex to implement Pros: the best of two modes; client prediction and interpolation can be used
  • 13. Pros of TCP: ● Reliable (in-order guaranteed delivery) ● If Web protocols are used, can pass through proxies and firewalls Cons of TCP: ● Retransmissions... If a segment is lost, newer data queues up in the server buffers until the initial segment is actually delivered. This provokes a clutter on the network, as bursts of aged data are sent out, with the risk of triggering a continuous packet loss on small-bandwidth networks. TCP vs. UDP
  • 14. A high-frequency stream of real-time data can be handled by a streaming server via queuing or resampling. In many cases, not all the data samples are needed. With resampling, the amount of data is reduced. Receiving less frequent updates does not mean receiving old updates. Resampling a real-time data flow is a procedure that needs to take several variables as input: ● unsampled data flow ● desired maximum frequency ● desired maximum bandwidth ● currently available bandwidth Data Resampling
  • 15. ● Bandwidth allocation: For each client, max bandwidth allocated to its multiplexed stream connection. Allocation can be changed on the fly. ● Frequency allocation: For each data flow of each client's multiplexed stream connection, max update rate can be allocated. Allocation can be changed on the fly. ● Real bandwidth detection: Internet congestions are detected and the server continuously adapt to the currently available bandwidth. The streaming server should heuristically combine these three categories of information to dynamically throttle the data flow applying resampling. Dynamic Throttling
  • 16. Instead of simply discarding updates, when resampling is done, the sender should try to merge them to save as much information as possible. Example: Event 1: X=5.1; Y=3.0; Z=2.3 Event 2: X=unchanged; Y=3.1; Z=2.5 Event 3: X=5.3; Y=unchanged; Z=2.8 If the resampling algorithms decides to drop event 2, the conflation mechanism will produce a single update, merging 2 and 3: Conflated event (2-3): X=5.3; Y=3.1; Z=2.8 Conflation
  • 17. Disable Nagle's algorithm (TCP_NODELAY). Pack updates efficiently into TCP segments. What is the maximum latency you can accept to forge bigger TCP segments and decrease the overheads (both network overheads and CPU overheads)? The highest the acceptable latency, the more data can be stuffed into the same TCP segment (batching), increasing overall performance. Batching
  • 18. Now please go to: bit.ly/mor777 (better with Chrome)
  • 19. We took the HTML5 version on Super Mario Bros. and made it multiplayer in a few hours... (it's not perfect, but gives an idea). Thanks to Josh Goldberg for creating the HTML5 version of Mario!
  • 20. triggers.js function keydown(event) { ... lsSendUserUpdate(event, 0); // Send key press event to Lightstreamer } function keyup(event) { ... lsSendUserUpdate(event, 1); // Send key press event to Lightstreamer } function lsSendUserUpdate(key, upOrDown) { lsClient.sendMessage(key + "|" + upOrDown + "|" + mario.left + "|" + mario.top + "|" + mario.power + "|" + gamescreen.left + "|" + gamescreen.top + "|" + currentmap[0] + "|" + currentmap[1] + "|" + area.setting, userGuid); } Sending local Mario's commands to the server (and piggybacking positions to correct drifts)
  • 21. Receiving remote Marios' commands from the server maps.js lsSubscription.addListener({ onItemUpdate: function(updateInfo) { try { var user = updateInfo.getValue("key"); var status = updateInfo.getValue("command"); switch (status) { case "ADD": lsProcessAddUser(user); break; case "DELETE": lsProcessDeleteUser(user); break; case "UPDATE": lsProcessUpdateUser(user, updateInfo); break; } } catch (e) { log(e); } } });
  • 22. maps.js function lsProcessUpdateUser(user, updateInfo) { ... var mario = window.otherMarios[user]; ... setLeft(mario, updateInfo.getValue("xLoc") + ...); setLeft(mario, updateInfo.getValue("yLoc") + ...); ... var involvedKey = parseInt(updateInfo.getValue("involvedKey")); var upOrDown = parseInt(updateInfo.getValue("upOrDown")); switch (upOrDown) { case 0: handleKeyDownUpdate(mario, involvedKey); break; case 1: handleKeyUpUpdate(mario, involvedKey); break; } Managing remote Marios' commands (together with piggybacked positions to correct drifts)
  • 23. Delta Delivery Lightweight Messages Instead of sending a full world snapshot at each update, send only the actual changes (delta) since the last update. Full snapshots are sent only at client startup and after disconnections. Avoid verbose data representations such as XML and JSON, which carry redundant metadata (field names) with each update. Go for lightweight representations, such as position based, to reduce message size.
  • 24. Automatic Detection of Best Transport There are still many cases in the real world where WebSockets are blocked by network intermediaries. Automatic and fast fall-back on a per-connection basis, to reach all clients. WebSocket HTTP Streaming HTTP Smart Polling WebSocket HTTP Streaming
  • 25. Contrary to common belief, the real advantage of WS over HTTP Streaming is in client-to-server messaging. Implement ordering, acknowledge, retransmissions, and baching even over HTTP, to reach all clients. Client-to-server In-order Guaranteed Message Delivery ServerBrowser ServerBrowser ServerBrowser TCP connection 1 TCP connection 1 TCP connection 2 WebSocket HTTP
  • 26. Now please go to: bit.ly/mor345
  • 27.
  • 28. You need a publish-subscribe paradigm to govern which messages should be delivered to which clients. With asymmetric pub-sub, the subscribers are on the client side and the publishers are on the server-side. Clients send messages to the publishers, which use them to create the actual messages to publish. Message Routing Data Adapter Client Publisher Subscriber sendMessage
  • 29. Subscriptions should be based on items and schemas (sets of fields) Item: object5 - Fields: "posX", "posY", "posZ", "rotX", "rotY", "rotZ", "rotW" Every client can subscribe to as many items it needs, each with its own schema: As a result, a multiplexed stream should be created: Subscription Model Client subscribes Field "A" Item1 Field "B" Field "C" Field "X" Item2 Field "Y" Field "A" Item3 Field "X" Field "C" Field "Y" Clientdelivers Item 1 snapshot Item 1 update 1 Item 2 snapshot Item 1 update 2 Item 2 update 1
  • 30. With the item-based approach, all the routing scenarios can be supported: broadcast, multicast, and unicast. Massive fan-out and individual messaging should be supported on the top of the same physical connections. Content-aware subscription modes can optimized data based on their semantics. Multiple Routing Scenarios publishes Item 1 publishes Item 1 (once) Data Adapter Client 1,000,000 Client 1 ... Massive fan-out, broadcast Data Adapter Client 2 Client 1 publishes Item 2 item 1 item 1 item 1 item 2 Personal messages, unicast
  • 31. Of course, your server needs to scale a lot to manage the real-time data for massively multiplayer online games. ● Use a concurrent staged-event driven architecture with non-blocking I/O. ● Automatically tune your thread pools based on the number of CPU cores. ● Enable graceful degradation. ● Support horizontal scalability via clustering. Results we got for a single server instance: ● One million clients, with a low message rate on each connection (a few updates per minute per client). ● Tens of thousands clients, with tens of messages per second per client. Scalability
  • 32. Commercial time :) Lightstreamer implements all the discussed techniques and much more! It's not open source, but free editions are available and we have a Startup Program to help new entrepreneurs. With 13 years of continuous evolution, it is the most widespread solution in the finance industry, now conquering several other verticals.
  • 33. Links Contact me - alessandro.alinone@lightstreamer.com - @alinone Optimizing Multiplayer 3D Game Synchronization Over the Web http://blog.lightstreamer.com/2013/10/optimizing-multiplayer-3d-game.html 3D World Demo http://demos.lightstreamer.com/3DWorldDemo