際際滷

際際滷Share a Scribd company logo
Unity and
WebSockets
Adventures in Mobile
Games
Josh Glover
Lead Backend Developer
Rock Science 2
What¨s a WebSocket?
¢ Bidirectional TCP connection
¢ Initiated from an HTTP connection by
sending Upgrade header
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYU=
Sec-WebSocket-Protocol: chat
Why WebSockets?
¢ Server can push messages instead of being
polled
¢ Polling often leads to large percentage of
request load being worthless
¢ Client disconnection can be part of API
Why not WebSockets?
¢ Servers can¨t be purely stateless
¢ How does a client on server A interact with a
client on server B?
¢ What happens when a server crashes?
¢ What if a client has a spotty network
connection?
Mix and match
¢ Use WebSockets where remote push is a
killer app
¢ Use plain old REST for everything else
¢ Gracefully degrade from WebSockets to
REST when network connectivity is poor
¢ HTTP Kit is a perfect fit!
¢ Open source C# WebSockets client
https://github.com/sta/websocket-sharp/
¢ Available on the Unity Asset Store
https://www.assetstore.unity3d.com/en/#!/content/8959
¢ With Unity 5, drop in your Assets folder and
compile away (full .NET 2.0 API only)
Connecting
using WebSocketSharp;
var ws = new WebSocket("ws://echo.websocket.org");
// We'll get to this
ws.OnOpen += OnOpenHandler;
ws.OnMessage += OnMessageHandler;
ws.OnClose += OnCloseHandler;
ws.OnError += OnErrorHandler;
ws.ConnectAsync();
private void OnOpenHandler(object sender, System.EventArgs e) {
Debug.Log("WebSocket connected!");
// Here is where you do useful stuff
}
How do I know when I¨m connected?
private void OnSendComplete(bool success) {
Debug.Log("Message sent successfully? " + success);
}
ws.SendAsync("This WebSockets stuff is a breeze!", OnSendComplete);
Sending a message
private void OnMessageHandler(object sender, MessageEventArgs e) {
Debug.Log("WebSocket server said: " + e.Data);
}
Receiving a message
private void OnCloseHandler(object sender, CloseEventArgs e) {
Debug.Log("WebSocket closed with reason: " + e.Reason);
}
ws.CloseAsync();
Disconnecting
Live Demo!
But wait, asynchronous means...
THREADS!
Unity threading model
¢ Single-threaded with coroutines
¢ API generally not thread-safe
¢ Anything that updates the screen must
happen on the main thread
websocket-sharp threading model
¢ .NET threads
¢ Anything done asynchronously happens on
a background thread
¢ Event handlers (OnOpen, OnMessage, etc.)
are invoked on background threads
And never the twain shall meet?
¢ This would be a (more) boring talk
¢ Enter our old Computer Science buddy, the
Finite State Machine
A simple state machine
using UnityEngine;
public enum State { NotRunning, Running, Connected, Ping, Pong, Done }
public delegate void Handler();
public class StateMachine : MonoBehaviour {
public void Run() { ´ }
public void Transition(State state) { ´ }
public void AddHandler(State state, Handler handler) { ´ }
public void Update() { ´ }
}
using System.Collections.Generic;
public class StateMachine : MonoBehaviour {
private readonly object syncLock = new object();
private readonly Queue<State> pending = new Queue<State>();
public void Transition(State state) {
lock(syncLock) {
pending.Enqueue(state);
}
}
}
Requesting transitions
public class StateMachine : MonoBehaviour {
private readonly Dictionary<State, Handler> handlers
= new Dictionary<State, Handler>();
public void AddHandler(State state, Handler handler) {
handlers.Add(state, handler);
}
}
Transition handlers
Handling transitions
public class StateMachine : MonoBehaviour {
public void Update() {
while (pending.Count > 0) {
currentState = pending.Dequeue();
Handler handler;
if (handlers.TryGetValue(currentState, out handler)) {
handler();
}
}
}
}
Start me up!
public class StateMachine : MonoBehaviour {
private State currentState = State.NotRunning;
public void Run() {
Transition(State.Running);
}
}
Putting it all together (1)
using UnityEngine;
using WebSocketSharp;
public class StatefulMain : MonoBehaviour {
public StateMachine stateMachine;
private WebSocket ws;
void Start() {
ws = new WebSocket("ws://echo.websocket.org");
ws.OnOpen += OnOpenHandler;
ws.OnMessage += OnMessageHandler;
ws.OnClose += OnCloseHandler;
Putting it all together (2)
stateMachine.AddHandler(State.Running, () => {
ws.ConnectAsync();
});
stateMachine.AddHandler(State.Connected, () => {
stateMachine.Transition(State.Ping);
});
stateMachine.AddHandler(State.Ping, () => {
ws.SendAsync("This WebSockets stuff is a breeze!",
OnSendComplete);
});
stateMachine.AddHandler(State.Pong, () => {
ws.CloseAsync();
});
private void OnOpenHandler(object sender, System.EventArgs e) {
Debug.Log("WebSocket connected!");
stateMachine.Transition(State.Connected);
}
private void OnMessageHandler(object sender, MessageEventArgs e) {
Debug.Log("WebSocket server said: " + e.Data);
stateMachine.Transition(State.Pong);
}
private void OnCloseHandler(object sender, CloseEventArgs e) {
Debug.Log("WebSocket closed with reason: " + e.Reason);
stateMachine.Transition(State.Done);
}
Putting it all together (3)
Putting it all together (4)
void Start() {
// WebSocket init code from previous slides
// State machine handlers from previous slides
stateMachine.Run();
}
Live Demo!
Use the Source, Luke
https://github.com/jmglov/unity-ws-demo

More Related Content

What's hot (20)

禽看界一艶姻から界看稼岳温庄稼艶姻糸への卞佩
禽看界一艶姻から界看稼岳温庄稼艶姻糸への卞佩禽看界一艶姻から界看稼岳温庄稼艶姻糸への卞佩
禽看界一艶姻から界看稼岳温庄稼艶姻糸への卞佩
Akihiro Suda
?
ネットワ`ク徭啝、なに聞う ゛徭啝ツ`ルB初゛(2017/08/18弖紗_岸)
ネットワ`ク徭啝、なに聞う ゛徭啝ツ`ルB初゛(2017/08/18弖紗_岸) ネットワ`ク徭啝、なに聞う ゛徭啝ツ`ルB初゛(2017/08/18弖紗_岸)
ネットワ`ク徭啝、なに聞う ゛徭啝ツ`ルB初゛(2017/08/18弖紗_岸)
akira6592
?
iostat await svctm の かた、深え圭
iostat await svctm の かた、深え圭iostat await svctm の かた、深え圭
iostat await svctm の かた、深え圭
i 会弥
?
Prometheus monitoring from outside of Kubernetes? ?と?うして厘?はKubernetes貧のPromet...
Prometheus monitoring from outside of Kubernetes? ?と?うして厘?はKubernetes貧のPromet...Prometheus monitoring from outside of Kubernetes? ?と?うして厘?はKubernetes貧のPromet...
Prometheus monitoring from outside of Kubernetes? ?と?うして厘?はKubernetes貧のPromet...
whywaita
?
オンライン麗尖バックアップの電麿モ`ドと掲電麿モ`ドについて┻15指PostgreSQLアンカンファレンス@オンライン k燕Y創
オンライン麗尖バックアップの電麿モ`ドと掲電麿モ`ドについて┻15指PostgreSQLアンカンファレンス@オンライン k燕Y創オンライン麗尖バックアップの電麿モ`ドと掲電麿モ`ドについて┻15指PostgreSQLアンカンファレンス@オンライン k燕Y創
オンライン麗尖バックアップの電麿モ`ドと掲電麿モ`ドについて┻15指PostgreSQLアンカンファレンス@オンライン k燕Y創
NTT DATA Technology & Innovation
?
佩ロックと仝LOG: process 12345 still waiting for ShareLock on transaction 710 afte...
佩ロックと仝LOG:  process 12345 still waiting for ShareLock on transaction 710 afte...佩ロックと仝LOG:  process 12345 still waiting for ShareLock on transaction 710 afte...
佩ロックと仝LOG: process 12345 still waiting for ShareLock on transaction 710 afte...
Masahiko Sawada
?
禽看界一艶姻た?けて?はないコンテナのはなし
禽看界一艶姻た?けて?はないコンテナのはなし禽看界一艶姻た?けて?はないコンテナのはなし
禽看界一艶姻た?けて?はないコンテナのはなし
Katsunori Kanda
?
いまさら療けない永看壊岳乙姻艶皆河晦塰喘砿尖
いまさら療けない永看壊岳乙姻艶皆河晦塰喘砿尖いまさら療けない永看壊岳乙姻艶皆河晦塰喘砿尖
いまさら療けない永看壊岳乙姻艶皆河晦塰喘砿尖
Uptime Technologies LLC (JP)
?
エキスパ`ト永霞岳鞄看稼プログラミング個匡3井のiみどころ
エキスパ`ト永霞岳鞄看稼プログラミング個匡3井のiみどころエキスパ`ト永霞岳鞄看稼プログラミング個匡3井のiみどころ
エキスパ`ト永霞岳鞄看稼プログラミング個匡3井のiみどころ
Takayuki Shimizukawa
?
java.lang.OutOfMemoryError #i紅java
java.lang.OutOfMemoryError #i紅javajava.lang.OutOfMemoryError #i紅java
java.lang.OutOfMemoryError #i紅java
Yuji Kubota
?
秘T Kubeflow ゛KubernetesでC亠僥をはじめるために゛ NTT Tech Conference #4 v處Y創
秘T Kubeflow ゛KubernetesでC亠僥をはじめるために゛ NTT Tech Conference #4 v處Y創秘T Kubeflow ゛KubernetesでC亠僥をはじめるために゛ NTT Tech Conference #4 v處Y創
秘T Kubeflow ゛KubernetesでC亠僥をはじめるために゛ NTT Tech Conference #4 v處Y創
NTT DATA Technology & Innovation
?
レプリケ`ションW决のOについて┻40指PostgreSQLアンカンファレンス@オンライン k燕Y創
レプリケ`ションW决のOについて┻40指PostgreSQLアンカンファレンス@オンライン k燕Y創レプリケ`ションW决のOについて┻40指PostgreSQLアンカンファレンス@オンライン k燕Y創
レプリケ`ションW决のOについて┻40指PostgreSQLアンカンファレンス@オンライン k燕Y創
NTT DATA Technology & Innovation
?
ジョブ砿尖で界姻看稼は渊腓あったので ̄檎顎稼糸艶界一 ̄を聞ってハッピ`になりました
ジョブ砿尖で界姻看稼は渊腓あったので ̄檎顎稼糸艶界一 ̄を聞ってハッピ`になりましたジョブ砿尖で界姻看稼は渊腓あったので ̄檎顎稼糸艶界一 ̄を聞ってハッピ`になりました
ジョブ砿尖で界姻看稼は渊腓あったので ̄檎顎稼糸艶界一 ̄を聞ってハッピ`になりました
Yukiya Hayashi
?
そんなトランサ?クションマネ`シ?ャて?寄嬋健か
そんなトランサ?クションマネ`シ?ャて?寄嬋健かそんなトランサ?クションマネ`シ?ャて?寄嬋健か
そんなトランサ?クションマネ`シ?ャて?寄嬋健か
takezoe
?
朕grep秘T +盾h
朕grep秘T +盾h朕grep秘T +盾h
朕grep秘T +盾h
murachue
?
Glibc malloc internal
Glibc malloc internalGlibc malloc internal
Glibc malloc internal
Motohiro KOSAKI
?
OAuth 2.0のResource Serverの恬り圭
OAuth 2.0のResource Serverの恬り圭OAuth 2.0のResource Serverの恬り圭
OAuth 2.0のResource Serverの恬り圭
Hitachi, Ltd. OSS Solution Center.
?
Kubernetesのしくみ やさしく僥ぶ 坪何夛とア`キテクチャ`
Kubernetesのしくみ やさしく僥ぶ 坪何夛とア`キテクチャ`Kubernetesのしくみ やさしく僥ぶ 坪何夛とア`キテクチャ`
Kubernetesのしくみ やさしく僥ぶ 坪何夛とア`キテクチャ`
Toru Makabe
?
まずやっとく永看壊岳乙姻艶皆河晦チュ`ニング
まずやっとく永看壊岳乙姻艶皆河晦チュ`ニングまずやっとく永看壊岳乙姻艶皆河晦チュ`ニング
まずやっとく永看壊岳乙姻艶皆河晦チュ`ニング
Kosuke Kida
?
永堰永の書とこれから2023
永堰永の書とこれから2023永堰永の書とこれから2023
永堰永の書とこれから2023
Rui Hirokawa
?
禽看界一艶姻から界看稼岳温庄稼艶姻糸への卞佩
禽看界一艶姻から界看稼岳温庄稼艶姻糸への卞佩禽看界一艶姻から界看稼岳温庄稼艶姻糸への卞佩
禽看界一艶姻から界看稼岳温庄稼艶姻糸への卞佩
Akihiro Suda
?
ネットワ`ク徭啝、なに聞う ゛徭啝ツ`ルB初゛(2017/08/18弖紗_岸)
ネットワ`ク徭啝、なに聞う ゛徭啝ツ`ルB初゛(2017/08/18弖紗_岸) ネットワ`ク徭啝、なに聞う ゛徭啝ツ`ルB初゛(2017/08/18弖紗_岸)
ネットワ`ク徭啝、なに聞う ゛徭啝ツ`ルB初゛(2017/08/18弖紗_岸)
akira6592
?
iostat await svctm の かた、深え圭
iostat await svctm の かた、深え圭iostat await svctm の かた、深え圭
iostat await svctm の かた、深え圭
i 会弥
?
Prometheus monitoring from outside of Kubernetes? ?と?うして厘?はKubernetes貧のPromet...
Prometheus monitoring from outside of Kubernetes? ?と?うして厘?はKubernetes貧のPromet...Prometheus monitoring from outside of Kubernetes? ?と?うして厘?はKubernetes貧のPromet...
Prometheus monitoring from outside of Kubernetes? ?と?うして厘?はKubernetes貧のPromet...
whywaita
?
オンライン麗尖バックアップの電麿モ`ドと掲電麿モ`ドについて┻15指PostgreSQLアンカンファレンス@オンライン k燕Y創
オンライン麗尖バックアップの電麿モ`ドと掲電麿モ`ドについて┻15指PostgreSQLアンカンファレンス@オンライン k燕Y創オンライン麗尖バックアップの電麿モ`ドと掲電麿モ`ドについて┻15指PostgreSQLアンカンファレンス@オンライン k燕Y創
オンライン麗尖バックアップの電麿モ`ドと掲電麿モ`ドについて┻15指PostgreSQLアンカンファレンス@オンライン k燕Y創
NTT DATA Technology & Innovation
?
佩ロックと仝LOG: process 12345 still waiting for ShareLock on transaction 710 afte...
佩ロックと仝LOG:  process 12345 still waiting for ShareLock on transaction 710 afte...佩ロックと仝LOG:  process 12345 still waiting for ShareLock on transaction 710 afte...
佩ロックと仝LOG: process 12345 still waiting for ShareLock on transaction 710 afte...
Masahiko Sawada
?
禽看界一艶姻た?けて?はないコンテナのはなし
禽看界一艶姻た?けて?はないコンテナのはなし禽看界一艶姻た?けて?はないコンテナのはなし
禽看界一艶姻た?けて?はないコンテナのはなし
Katsunori Kanda
?
いまさら療けない永看壊岳乙姻艶皆河晦塰喘砿尖
いまさら療けない永看壊岳乙姻艶皆河晦塰喘砿尖いまさら療けない永看壊岳乙姻艶皆河晦塰喘砿尖
いまさら療けない永看壊岳乙姻艶皆河晦塰喘砿尖
Uptime Technologies LLC (JP)
?
エキスパ`ト永霞岳鞄看稼プログラミング個匡3井のiみどころ
エキスパ`ト永霞岳鞄看稼プログラミング個匡3井のiみどころエキスパ`ト永霞岳鞄看稼プログラミング個匡3井のiみどころ
エキスパ`ト永霞岳鞄看稼プログラミング個匡3井のiみどころ
Takayuki Shimizukawa
?
java.lang.OutOfMemoryError #i紅java
java.lang.OutOfMemoryError #i紅javajava.lang.OutOfMemoryError #i紅java
java.lang.OutOfMemoryError #i紅java
Yuji Kubota
?
秘T Kubeflow ゛KubernetesでC亠僥をはじめるために゛ NTT Tech Conference #4 v處Y創
秘T Kubeflow ゛KubernetesでC亠僥をはじめるために゛ NTT Tech Conference #4 v處Y創秘T Kubeflow ゛KubernetesでC亠僥をはじめるために゛ NTT Tech Conference #4 v處Y創
秘T Kubeflow ゛KubernetesでC亠僥をはじめるために゛ NTT Tech Conference #4 v處Y創
NTT DATA Technology & Innovation
?
レプリケ`ションW决のOについて┻40指PostgreSQLアンカンファレンス@オンライン k燕Y創
レプリケ`ションW决のOについて┻40指PostgreSQLアンカンファレンス@オンライン k燕Y創レプリケ`ションW决のOについて┻40指PostgreSQLアンカンファレンス@オンライン k燕Y創
レプリケ`ションW决のOについて┻40指PostgreSQLアンカンファレンス@オンライン k燕Y創
NTT DATA Technology & Innovation
?
ジョブ砿尖で界姻看稼は渊腓あったので ̄檎顎稼糸艶界一 ̄を聞ってハッピ`になりました
ジョブ砿尖で界姻看稼は渊腓あったので ̄檎顎稼糸艶界一 ̄を聞ってハッピ`になりましたジョブ砿尖で界姻看稼は渊腓あったので ̄檎顎稼糸艶界一 ̄を聞ってハッピ`になりました
ジョブ砿尖で界姻看稼は渊腓あったので ̄檎顎稼糸艶界一 ̄を聞ってハッピ`になりました
Yukiya Hayashi
?
そんなトランサ?クションマネ`シ?ャて?寄嬋健か
そんなトランサ?クションマネ`シ?ャて?寄嬋健かそんなトランサ?クションマネ`シ?ャて?寄嬋健か
そんなトランサ?クションマネ`シ?ャて?寄嬋健か
takezoe
?
朕grep秘T +盾h
朕grep秘T +盾h朕grep秘T +盾h
朕grep秘T +盾h
murachue
?
Kubernetesのしくみ やさしく僥ぶ 坪何夛とア`キテクチャ`
Kubernetesのしくみ やさしく僥ぶ 坪何夛とア`キテクチャ`Kubernetesのしくみ やさしく僥ぶ 坪何夛とア`キテクチャ`
Kubernetesのしくみ やさしく僥ぶ 坪何夛とア`キテクチャ`
Toru Makabe
?
まずやっとく永看壊岳乙姻艶皆河晦チュ`ニング
まずやっとく永看壊岳乙姻艶皆河晦チュ`ニングまずやっとく永看壊岳乙姻艶皆河晦チュ`ニング
まずやっとく永看壊岳乙姻艶皆河晦チュ`ニング
Kosuke Kida
?
永堰永の書とこれから2023
永堰永の書とこれから2023永堰永の書とこれから2023
永堰永の書とこれから2023
Rui Hirokawa
?

Viewers also liked (15)

WebSockets, Unity3D, and Clojure
WebSockets, Unity3D, and ClojureWebSockets, Unity3D, and Clojure
WebSockets, Unity3D, and Clojure
Josh Glover
?
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScript
Leonardo Borges
?
???3D ??? ???
???3D ??? ??????3D ??? ???
???3D ??? ???
?? ?
?
ゲ`ム_k兜伉宀のWがUnity + WebSocketで採か恬ってみた
ゲ`ム_k兜伉宀のWがUnity + WebSocketで採か恬ってみたゲ`ム_k兜伉宀のWがUnity + WebSocketで採か恬ってみた
ゲ`ム_k兜伉宀のWがUnity + WebSocketで採か恬ってみた
Kohei Kadowaki
?
Clojure@Nuday
Clojure@NudayClojure@Nuday
Clojure@Nuday
Josh Glover
?
Kinect2 hands on
Kinect2 hands onKinect2 hands on
Kinect2 hands on
Luigi Oliveto
?
Переименования на оккупированном Донбассе
Переименования на оккупированном ДонбассеПереименования на оккупированном Донбассе
Переименования на оккупированном Донбассе
Andrew Vodianyi
?
Construindo aplica??es com HTML5, WebSockets, e Java EE 7
Construindo aplica??es com HTML5, WebSockets, e Java EE 7Construindo aplica??es com HTML5, WebSockets, e Java EE 7
Construindo aplica??es com HTML5, WebSockets, e Java EE 7
Bruno Borges
?
Introduction to WebSockets
Introduction to WebSocketsIntroduction to WebSockets
Introduction to WebSockets
WASdev Community
?
Introduction to WebSockets
Introduction to WebSocketsIntroduction to WebSockets
Introduction to WebSockets
Gunnar Hillert
?
Space Ape's Live Ops Stack: Engineering Mobile Games for Live Ops from Day 1
Space Ape's Live Ops Stack: Engineering Mobile Games for Live Ops from Day 1Space Ape's Live Ops Stack: Engineering Mobile Games for Live Ops from Day 1
Space Ape's Live Ops Stack: Engineering Mobile Games for Live Ops from Day 1
Simon Hade
?
Семь тысяч Rps, один go
Семь тысяч Rps, один goСемь тысяч Rps, один go
Семь тысяч Rps, один go
Badoo Development
?
Thrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased ComparisonThrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased Comparison
Igor Anishchenko
?
Victoria's Secret Angels Campaign
Victoria's Secret Angels CampaignVictoria's Secret Angels Campaign
Victoria's Secret Angels Campaign
John White
?
WebSockets, Unity3D, and Clojure
WebSockets, Unity3D, and ClojureWebSockets, Unity3D, and Clojure
WebSockets, Unity3D, and Clojure
Josh Glover
?
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScript
Leonardo Borges
?
???3D ??? ???
???3D ??? ??????3D ??? ???
???3D ??? ???
?? ?
?
ゲ`ム_k兜伉宀のWがUnity + WebSocketで採か恬ってみた
ゲ`ム_k兜伉宀のWがUnity + WebSocketで採か恬ってみたゲ`ム_k兜伉宀のWがUnity + WebSocketで採か恬ってみた
ゲ`ム_k兜伉宀のWがUnity + WebSocketで採か恬ってみた
Kohei Kadowaki
?
Переименования на оккупированном Донбассе
Переименования на оккупированном ДонбассеПереименования на оккупированном Донбассе
Переименования на оккупированном Донбассе
Andrew Vodianyi
?
Construindo aplica??es com HTML5, WebSockets, e Java EE 7
Construindo aplica??es com HTML5, WebSockets, e Java EE 7Construindo aplica??es com HTML5, WebSockets, e Java EE 7
Construindo aplica??es com HTML5, WebSockets, e Java EE 7
Bruno Borges
?
Introduction to WebSockets
Introduction to WebSocketsIntroduction to WebSockets
Introduction to WebSockets
Gunnar Hillert
?
Space Ape's Live Ops Stack: Engineering Mobile Games for Live Ops from Day 1
Space Ape's Live Ops Stack: Engineering Mobile Games for Live Ops from Day 1Space Ape's Live Ops Stack: Engineering Mobile Games for Live Ops from Day 1
Space Ape's Live Ops Stack: Engineering Mobile Games for Live Ops from Day 1
Simon Hade
?
Семь тысяч Rps, один go
Семь тысяч Rps, один goСемь тысяч Rps, один go
Семь тысяч Rps, один go
Badoo Development
?
Thrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased ComparisonThrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased Comparison
Igor Anishchenko
?
Victoria's Secret Angels Campaign
Victoria's Secret Angels CampaignVictoria's Secret Angels Campaign
Victoria's Secret Angels Campaign
John White
?

Similar to Unity and WebSockets (20)

Enhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocketEnhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocket
Mauricio "Maltron" Leal
?
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web Sockets
Fahad Golra
?
Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012
Sameer Segal
?
Web Real-time Communications
Web Real-time CommunicationsWeb Real-time Communications
Web Real-time Communications
Alexei Skachykhin
?
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
Gonzalo Ayuso
?
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
Wim Godden
?
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
Srikanth Reddy Pallerla
?
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
Yakov Fain
?
5.node js
5.node js5.node js
5.node js
Geunhyung Kim
?
Reactive server with netty
Reactive server with nettyReactive server with netty
Reactive server with netty
Dmitriy Dumanskiy
?
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
Naresh Chintalcheru
?
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
Carol McDonald
?
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
Pawe? Kowalczuk
?
Building Websocket Applications with GlassFish and Grizzly
Building Websocket Applications with GlassFish and GrizzlyBuilding Websocket Applications with GlassFish and Grizzly
Building Websocket Applications with GlassFish and Grizzly
Justin Lee
?
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
Wim Godden
?
Html5 websockets
Html5 websocketsHtml5 websockets
Html5 websockets
AbhishekMondal42
?
Websocket
WebsocketWebsocket
Websocket
Masudul Haque
?
WebSockets Jump Start
WebSockets Jump StartWebSockets Jump Start
WebSockets Jump Start
Haim Michael
?
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
Ericom Software
?
WebSockets in JEE 7
WebSockets in JEE 7WebSockets in JEE 7
WebSockets in JEE 7
Shahzad Badar
?
Enhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocketEnhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocket
Mauricio "Maltron" Leal
?
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web Sockets
Fahad Golra
?
Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012
Sameer Segal
?
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
Wim Godden
?
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
Polling Techniques, Ajax, protocol Switching from Http to Websocket standard ...
Srikanth Reddy Pallerla
?
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
Yakov Fain
?
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
Naresh Chintalcheru
?
Building Websocket Applications with GlassFish and Grizzly
Building Websocket Applications with GlassFish and GrizzlyBuilding Websocket Applications with GlassFish and Grizzly
Building Websocket Applications with GlassFish and Grizzly
Justin Lee
?
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
Wim Godden
?
WebSockets Jump Start
WebSockets Jump StartWebSockets Jump Start
WebSockets Jump Start
Haim Michael
?
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
Ericom Software
?

Unity and WebSockets

  • 1. Unity and WebSockets Adventures in Mobile Games Josh Glover Lead Backend Developer
  • 3. What¨s a WebSocket? ¢ Bidirectional TCP connection ¢ Initiated from an HTTP connection by sending Upgrade header GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Origin: http://example.com HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYU= Sec-WebSocket-Protocol: chat
  • 4. Why WebSockets? ¢ Server can push messages instead of being polled ¢ Polling often leads to large percentage of request load being worthless ¢ Client disconnection can be part of API
  • 5. Why not WebSockets? ¢ Servers can¨t be purely stateless ¢ How does a client on server A interact with a client on server B? ¢ What happens when a server crashes? ¢ What if a client has a spotty network connection?
  • 6. Mix and match ¢ Use WebSockets where remote push is a killer app ¢ Use plain old REST for everything else ¢ Gracefully degrade from WebSockets to REST when network connectivity is poor ¢ HTTP Kit is a perfect fit!
  • 7. ¢ Open source C# WebSockets client https://github.com/sta/websocket-sharp/ ¢ Available on the Unity Asset Store https://www.assetstore.unity3d.com/en/#!/content/8959 ¢ With Unity 5, drop in your Assets folder and compile away (full .NET 2.0 API only)
  • 8. Connecting using WebSocketSharp; var ws = new WebSocket("ws://echo.websocket.org"); // We'll get to this ws.OnOpen += OnOpenHandler; ws.OnMessage += OnMessageHandler; ws.OnClose += OnCloseHandler; ws.OnError += OnErrorHandler; ws.ConnectAsync();
  • 9. private void OnOpenHandler(object sender, System.EventArgs e) { Debug.Log("WebSocket connected!"); // Here is where you do useful stuff } How do I know when I¨m connected?
  • 10. private void OnSendComplete(bool success) { Debug.Log("Message sent successfully? " + success); } ws.SendAsync("This WebSockets stuff is a breeze!", OnSendComplete); Sending a message
  • 11. private void OnMessageHandler(object sender, MessageEventArgs e) { Debug.Log("WebSocket server said: " + e.Data); } Receiving a message
  • 12. private void OnCloseHandler(object sender, CloseEventArgs e) { Debug.Log("WebSocket closed with reason: " + e.Reason); } ws.CloseAsync(); Disconnecting
  • 14. But wait, asynchronous means... THREADS!
  • 15. Unity threading model ¢ Single-threaded with coroutines ¢ API generally not thread-safe ¢ Anything that updates the screen must happen on the main thread
  • 16. websocket-sharp threading model ¢ .NET threads ¢ Anything done asynchronously happens on a background thread ¢ Event handlers (OnOpen, OnMessage, etc.) are invoked on background threads
  • 17. And never the twain shall meet? ¢ This would be a (more) boring talk ¢ Enter our old Computer Science buddy, the Finite State Machine
  • 18. A simple state machine using UnityEngine; public enum State { NotRunning, Running, Connected, Ping, Pong, Done } public delegate void Handler(); public class StateMachine : MonoBehaviour { public void Run() { ´ } public void Transition(State state) { ´ } public void AddHandler(State state, Handler handler) { ´ } public void Update() { ´ } }
  • 19. using System.Collections.Generic; public class StateMachine : MonoBehaviour { private readonly object syncLock = new object(); private readonly Queue<State> pending = new Queue<State>(); public void Transition(State state) { lock(syncLock) { pending.Enqueue(state); } } } Requesting transitions
  • 20. public class StateMachine : MonoBehaviour { private readonly Dictionary<State, Handler> handlers = new Dictionary<State, Handler>(); public void AddHandler(State state, Handler handler) { handlers.Add(state, handler); } } Transition handlers
  • 21. Handling transitions public class StateMachine : MonoBehaviour { public void Update() { while (pending.Count > 0) { currentState = pending.Dequeue(); Handler handler; if (handlers.TryGetValue(currentState, out handler)) { handler(); } } } }
  • 22. Start me up! public class StateMachine : MonoBehaviour { private State currentState = State.NotRunning; public void Run() { Transition(State.Running); } }
  • 23. Putting it all together (1) using UnityEngine; using WebSocketSharp; public class StatefulMain : MonoBehaviour { public StateMachine stateMachine; private WebSocket ws; void Start() { ws = new WebSocket("ws://echo.websocket.org"); ws.OnOpen += OnOpenHandler; ws.OnMessage += OnMessageHandler; ws.OnClose += OnCloseHandler;
  • 24. Putting it all together (2) stateMachine.AddHandler(State.Running, () => { ws.ConnectAsync(); }); stateMachine.AddHandler(State.Connected, () => { stateMachine.Transition(State.Ping); }); stateMachine.AddHandler(State.Ping, () => { ws.SendAsync("This WebSockets stuff is a breeze!", OnSendComplete); }); stateMachine.AddHandler(State.Pong, () => { ws.CloseAsync(); });
  • 25. private void OnOpenHandler(object sender, System.EventArgs e) { Debug.Log("WebSocket connected!"); stateMachine.Transition(State.Connected); } private void OnMessageHandler(object sender, MessageEventArgs e) { Debug.Log("WebSocket server said: " + e.Data); stateMachine.Transition(State.Pong); } private void OnCloseHandler(object sender, CloseEventArgs e) { Debug.Log("WebSocket closed with reason: " + e.Reason); stateMachine.Transition(State.Done); } Putting it all together (3)
  • 26. Putting it all together (4) void Start() { // WebSocket init code from previous slides // State machine handlers from previous slides stateMachine.Run(); }
  • 28. Use the Source, Luke https://github.com/jmglov/unity-ws-demo