SlideShare a Scribd company logo
ASP.NET CORE 帶您
讀源碼
WebSocket 篇
WebSocket
■ Duplex bi-directional Api for web
server  client
■ RFC 6455
https://tools.ietf.org/html/rfc6455
■ W3C standard:
https://www.w3.org/TR/websockets
/
■ Transport protocol intro:
https://www.youtube.com/watch?v=
9FqjRN4VYUU
■ Js Client & protocol packet format
intro: https://hpbn.co/websocket/
WebSocket
Connect State Transition
1. Connection Upgrade
(Protocol Switch)
2. Data In/Out arbitrarily
(Ping  Pong to detect online)
3. Close connection handshake
Transfer “Frame” format
Read the source?!
Experiment with source!!
(tracing/logging or make it
debuggable)■ Client :
websocket-sharp
https://sta.github.io/websocket-
sharp/
■ Server :
ASP.NET Core v2.1.1 Websocket
https://docs.microsoft.com/en-
us/aspnet/core/fundamentals/webso
ckets?view=aspnetcore-2.1
websocket-sharp
■ Run on .NET Framework 3.5 and above, Mono, Unity3D
■ A single DLL provide websocket client/server functionality, comply with RFC 6455
■ HTTPS encrypt/decrypt algorithm is via Framework functionality
■ MIT license
websocket-sharp
■ Client usage is very simple:
https://github.com/sta/websocket-
sharp#websocket-client
■ Has event hook let client handler websocket event
easily: http://bit.ly/2ztELl9
■ Mimic Js Websocket API:
https://developer.mozilla.org/en-
US/docs/Web/API/WebSocket
■ Entry Point: the “WebSocket” class: http://bit.ly/2L76Xf2
■ WebSocket Connect() Implementation:
– Connect() API : http://bit.ly/2KVjLsf
 doHandshake() : http://bit.ly/2J9ySJn
 setClientStream() : http://bit.ly/2zsdLCN
 createHandshakeRequest() : http://bit.ly/2KKAkHO
 sendHttpRequest() : http://bit.ly/2JeiYgX
 checkHandshakeResponse() : http://bit.ly/2zsim7O
=> Create “NetworkStream (http://bit.ly/2L3q5xE)” for afterward R/W operation
■ WebSocket Send() Implementation:
– Send() API : http://bit.ly/2LaYY0I
 send(Opcode opcode, Stream stream, bool compressed) : http://bit.ly/2N31aYq
 send(Fin fin, Opcode opcode, byte[] data, bool compressed) : http://bit.ly/2KPszQQ
 sendBytes(byte[] bytes) : http://bit.ly/2zoQCkx
=> Wrap input into a lot of “WebSocketFrame (http://bit.ly/2N5zfHh)” then write to stream
■ WebSocket OnMessage event Implementation:
– EventHandler<MessageEventArgs> OnMessage :
■ There’re two place emit the event:
– messagec(MessageEventArgs e) : http://bit.ly/2L7etGO
■ This is binding to Action<> _message field, which is invoked On:
– open() : http://bit.ly/2uaCGpl
■ Being called at Connect() API : http://bit.ly/2L65rgE
– message() : http://bit.ly/2KMUt00
– startReceiving() : http://bit.ly/2NEcATw
– open() : http://bit.ly/2zssHAE
=> Get data from internal _messageEventQueue.Dequeue() then invoke the event.
ASP.NET Core Websocket Server
■ The whole implementation across many “Nuget Packges (https://www.nuget.org/packages)”:
– Microsoft.AspNetCore.Websockets
– Microsoft.AspNetCore.Http.Abstractions
– Microsoft.AspNetCore.Http
– Microsoft.AspNetCore.Http.Extensions
– Microsoft.AspNetCore.Http.Features
– Microsoft.AspNetCore.Server.Kestrel
– Microsoft.AspNetCore.Server.Kestrel.Core
– System.Net.WebSockets.WebSocketProtocol
– System.Net.WebSockets
■ It’s impossible to get through whole source code simply by human 👀!!!
■ We have to “experiment it” with debuggable source code or being able to logging detail
information.
Build ASP.Net Core Framework
Package
(make it debuggable)■ Build debuggable ASP.NET Core nuget packages?
1. Clone the official build repo: Universe https://github.com/aspnet/Universe
2. Build it…...since ASP.NET Core module’s source has almost unified folder
structure convention:
■ src: The real source code
■ test: Testing code
■ sample: sample project or test to verify production source
■ build: build configuration files
■ Write a example project to use those debuggable packages then run it, dive into….
WebSocket on client & server using websocket-sharp & ASP.NET Core
Build ASP.Net Core Framework Package
■ To build individual packages:
1. In Windows machine, Install chocolatey, git for windows, Visual Studio 2017
and ASP.NET workload, node.js (for npm):
https://github.com/aspnet/Universe/wiki/Setting-a-machine-up-to-run-Universe
2. Clone Universe repo with correct tag ( -b 2.1.1), be sure to use --recursive to
get associated git submodule repo in modules folder.
3. Run build.cmd (build.sh) on top folder to let ASP.NET Core Buildtools setup
correct config files on first time, even if not all module can successful build.
4. Make sure the residue build process are all killed.
5. Switch to the module folder you want to build, delete anything in
artifactsbuild subfolder, then use:
build.cmd /p:CompileOnly=true /p:SkipTests=true
To build those Nuget packages of the module, Resulting files will reside in
module folder's artifactsbuild folder, and by default, they are debuggable.
Build ASP.Net Core Framework
Package
(make it debuggable)■ Use “find –iname“ or “dir /s” to find Nuget packages real source location in
Universe repo:
■ Exception:
Microsoft.AspNetCore.Server.Kestrel
Microsoft.AspNetCore.Server.Kestrel.Core
is in modulesKestrelHttpServer folder
■ But the
System.Net.WebSockets.WebSocketProtocol
System.Net.WebSockets
packages are .NET Core runtime’s built-in libraries, that belongs to the
“CoreFx (https://github.com/dotnet/corefx)” repo, not in ASP.NET Core
Time Savior: SourceLink support in
VisualStudio
(https://github.com/dotnet/sourcelink )
■ Visual Studio 2017 v15.7 and above support
SourceLink ( https://docs.microsoft.com/en-
us/visualstudio/releasenotes/vs2017-
relnotes#debug) ,
■ Begin from ASP.NET Core 2.0 it support
SourceLink too:
https://github.com/dotnet/core/issues/897,
but some packages may not ready:
https://github.com/dotnet/buildtools/issues/
1896
■ Most of time it just works 👍
■ Caveat:
– Can not use “GoToDefinition(F12)” if it hasn’t been using debugger dive into it.
– If source code already disappear on GitHub, it cannot work.
– Some too deep function(s) may not work (may be bug?!)
Example experiment project
■ Example source repo:
http://bit.ly/2KO3B4n
■ It use .NET Core SCD deployment
(http://bit.ly/2maxCgj)to let
ASP.NET core runtime use
debuggable Nuget packages we
created.
■ Runs only on Win10-x64
machine.
WebSocket on client & server using websocket-sharp & ASP.NET Core
Some interesting digging result: (1)
■ WebSocket connection setup is implmented in “DefaultWebSocketManager”, its
AccetpWebSocketAsync() is forwarding Websocket upgrade connection work to
WebSocketMiddleware: http://bit.ly/2ukREs1
■ WebSocket SHA-1 encrypt key is hard-coded: http://bit.ly/2N2oTYT
Some interesting digging result: (2)
■ The real “Connection Upgrade” phase is done in
Microsoft.AspNetCore.Server.Kestrel
nuget package’s code, which is Web Server itself:
http://bit.ly/2umVGjz
■ And the WebSocket(http://bit.ly/2KO5uhK) instance is created from websocket
middleware using “HttpResponseStream” as source, the real class is
“ManagedWebSocket”, an internal un-documented Class:
Some interesting digging result: (3)
■ The Actual ReadAsync() & WriteAsync() implementation entry point is extension
methods: http://bit.ly/2uo2ZaL
■ Write data to websocket’s final operations is call HttpUpgradeStream’s
WriteAsync(), which is also located in Web Server itself (the
Microsoft.AspNetCore.Server.Kestrel.Core Nuget package) :
http://bit.ly/2uaKk33
■ Closing websocket implementation is done by ManagedWebSocket class itself:
http://bit.ly/2mbw9pW
WebSocket’s ReadAsync() final operation:
WebSocket’s WriteAsync() final operation:
Conclusion
■ ASP.NET Core use many Abstract class and Interface in its API, and the real
implementation is DefaultOOXX most of the time.
Ex:
WebSocketManager  DefaultWebSocketManager
HttpContext  DefaultHttpContext
■ ASP.NET Core’s Middleware is binding via “Microsoft.AspNetCore.Http.Features”
Nuget’s code.
Resources & Tools:
■ SourceGrpah: https://sourcegraph.com/
■ VSCode & OmniSharp extension:
https://code.visualstudio.com/Docs/languages/csharp
■ MDN:
– Websocket API: https://developer.mozilla.org/en-
US/docs/Web/API/Websockets_API
– Writing WebSocket servers: https://developer.mozilla.org/en-
US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers

More Related Content

What's hot (19)

PPT
Decision tree and random forest
Lippo Group Digital
 
PPTX
Bayesian Classification
Gang Tao
 
PPTX
Machine Learning with H2O
Sri Ambati
 
PDF
Machine Learning and Data Mining: 13 Nearest Neighbor and Bayesian Classifiers
Pier Luca Lanzi
 
PPTX
Electronic mail - Computer Networks
Umme Jamal
 
PPTX
Chapter 10: Error Correction and Detection
JeoffnaRuth
 
PDF
Bayesian networks
Massimiliano Patacchiola
 
PPTX
Decision tree
Venkata Reddy Konasani
 
PPTX
Physical layer OSI Model & Transmission Media
Mukesh Chinta
 
PDF
Physical Layer Numericals - Data Communication & Networking
Drishti Bhalla
 
PDF
Cs8601 3
Kathirvel Ayyaswamy
 
PPT
Switching
Shankar Gangaju
 
PDF
Machine Learning: Applications, Process and Techniques
Rui Pedro Paiva
 
PPTX
Flow control &amp; error control
ManishTadhiyal
 
PDF
A WHITE BOX TESTING TECHNIQUE IN SOFTWARE TESTING : BASIS PATH TESTING
Journal For Research
 
PDF
Classification Based Machine Learning Algorithms
Md. Main Uddin Rony
 
PPT
Loops and functions in r
manikanta361
 
PPTX
Proximal Policy Optimization
ShubhaManikarnike
 
Decision tree and random forest
Lippo Group Digital
 
Bayesian Classification
Gang Tao
 
Machine Learning with H2O
Sri Ambati
 
Machine Learning and Data Mining: 13 Nearest Neighbor and Bayesian Classifiers
Pier Luca Lanzi
 
Electronic mail - Computer Networks
Umme Jamal
 
Chapter 10: Error Correction and Detection
JeoffnaRuth
 
Bayesian networks
Massimiliano Patacchiola
 
Decision tree
Venkata Reddy Konasani
 
Physical layer OSI Model & Transmission Media
Mukesh Chinta
 
Physical Layer Numericals - Data Communication & Networking
Drishti Bhalla
 
Switching
Shankar Gangaju
 
Machine Learning: Applications, Process and Techniques
Rui Pedro Paiva
 
Flow control &amp; error control
ManishTadhiyal
 
A WHITE BOX TESTING TECHNIQUE IN SOFTWARE TESTING : BASIS PATH TESTING
Journal For Research
 
Classification Based Machine Learning Algorithms
Md. Main Uddin Rony
 
Loops and functions in r
manikanta361
 
Proximal Policy Optimization
ShubhaManikarnike
 

Similar to WebSocket on client & server using websocket-sharp & ASP.NET Core (20)

PPTX
ASP.NET Core 2.1: The Future of Web Apps
Shahed Chowdhuri
 
PDF
"Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R...
Fwdays
 
PPTX
ASP.NET Core 2.1: The Future of Web Apps
Shahed Chowdhuri
 
PPTX
ASP.NET Core 2.1: The Future of Web Apps
Shahed Chowdhuri
 
PPTX
Realtime web experience with signal r
Ran Wahle
 
PDF
An In-Depth Comparison of WebSocket and SignalR: Pros, Cons, and Use Cases
Tien Nguyen
 
PPTX
Real-Time Communication
ssusere19c741
 
PPTX
Training Webinar: Enterprise application performance with server push technol...
OutSystems
 
PDF
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
PROIDEA
 
PPTX
WebSockets-Revolutionizing-Real-Time-Communication.pptx
YasserLina
 
PPTX
Building Real time Application with Azure SignalR Service
Jalpesh Vadgama
 
PPTX
Server interaction with web socket protocol
Rahul Rai
 
PPTX
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher
 
PPTX
Connected Web Systems
Damir Dobric
 
PPTX
Come ti "pusho" il web con WebSockets: da 0 a SignalR
Alessandro Melchiori
 
PDF
WebSocket Push Fallback - Transcript.pdf
ShaiAlmog1
 
PPTX
Xamarin Form using ASP.NET Core SignalR client
Chen Yu Pao
 
PPTX
What should you know about Net Core?
Damir Dobric
 
PPTX
.NET Core Today and Tomorrow
Jon Galloway
 
PPTX
How To Build Real-Time Applications With ASP.NET Core SignalR
IntelliSource Technologies
 
ASP.NET Core 2.1: The Future of Web Apps
Shahed Chowdhuri
 
"Hidden difficulties of debugger implementation for .NET WASM apps", Andrii R...
Fwdays
 
ASP.NET Core 2.1: The Future of Web Apps
Shahed Chowdhuri
 
ASP.NET Core 2.1: The Future of Web Apps
Shahed Chowdhuri
 
Realtime web experience with signal r
Ran Wahle
 
An In-Depth Comparison of WebSocket and SignalR: Pros, Cons, and Use Cases
Tien Nguyen
 
Real-Time Communication
ssusere19c741
 
Training Webinar: Enterprise application performance with server push technol...
OutSystems
 
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
PROIDEA
 
WebSockets-Revolutionizing-Real-Time-Communication.pptx
YasserLina
 
Building Real time Application with Azure SignalR Service
Jalpesh Vadgama
 
Server interaction with web socket protocol
Rahul Rai
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher
 
Connected Web Systems
Damir Dobric
 
Come ti "pusho" il web con WebSockets: da 0 a SignalR
Alessandro Melchiori
 
WebSocket Push Fallback - Transcript.pdf
ShaiAlmog1
 
Xamarin Form using ASP.NET Core SignalR client
Chen Yu Pao
 
What should you know about Net Core?
Damir Dobric
 
.NET Core Today and Tomorrow
Jon Galloway
 
How To Build Real-Time Applications With ASP.NET Core SignalR
IntelliSource Technologies
 
Ad

More from Chen Yu Pao (7)

PPTX
HoloLens 2的 MR(Mixed Reality)開發入門
Chen Yu Pao
 
PPTX
SkiaSharp on Xamarin Forms
Chen Yu Pao
 
PPTX
ReactiveUI Xamarin.Forms
Chen Yu Pao
 
PPTX
Xamarin ARKit Introduction 01
Chen Yu Pao
 
PPTX
Xamarin native forms
Chen Yu Pao
 
PPTX
Xamarin的Azure後端懶人包
Chen Yu Pao
 
PPTX
Proto actor 串接 Go 與 C# 簡易上手
Chen Yu Pao
 
HoloLens 2的 MR(Mixed Reality)開發入門
Chen Yu Pao
 
SkiaSharp on Xamarin Forms
Chen Yu Pao
 
ReactiveUI Xamarin.Forms
Chen Yu Pao
 
Xamarin ARKit Introduction 01
Chen Yu Pao
 
Xamarin native forms
Chen Yu Pao
 
Xamarin的Azure後端懶人包
Chen Yu Pao
 
Proto actor 串接 Go 與 C# 簡易上手
Chen Yu Pao
 
Ad

Recently uploaded (20)

PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 

WebSocket on client & server using websocket-sharp & ASP.NET Core

  • 2. WebSocket ■ Duplex bi-directional Api for web server  client ■ RFC 6455 https://tools.ietf.org/html/rfc6455 ■ W3C standard: https://www.w3.org/TR/websockets / ■ Transport protocol intro: https://www.youtube.com/watch?v= 9FqjRN4VYUU ■ Js Client & protocol packet format intro: https://hpbn.co/websocket/
  • 3. WebSocket Connect State Transition 1. Connection Upgrade (Protocol Switch) 2. Data In/Out arbitrarily (Ping  Pong to detect online) 3. Close connection handshake Transfer “Frame” format
  • 5. Experiment with source!! (tracing/logging or make it debuggable)■ Client : websocket-sharp https://sta.github.io/websocket- sharp/ ■ Server : ASP.NET Core v2.1.1 Websocket https://docs.microsoft.com/en- us/aspnet/core/fundamentals/webso ckets?view=aspnetcore-2.1
  • 6. websocket-sharp ■ Run on .NET Framework 3.5 and above, Mono, Unity3D ■ A single DLL provide websocket client/server functionality, comply with RFC 6455 ■ HTTPS encrypt/decrypt algorithm is via Framework functionality ■ MIT license
  • 7. websocket-sharp ■ Client usage is very simple: https://github.com/sta/websocket- sharp#websocket-client ■ Has event hook let client handler websocket event easily: http://bit.ly/2ztELl9 ■ Mimic Js Websocket API: https://developer.mozilla.org/en- US/docs/Web/API/WebSocket
  • 8. ■ Entry Point: the “WebSocket” class: http://bit.ly/2L76Xf2 ■ WebSocket Connect() Implementation: – Connect() API : http://bit.ly/2KVjLsf  doHandshake() : http://bit.ly/2J9ySJn  setClientStream() : http://bit.ly/2zsdLCN  createHandshakeRequest() : http://bit.ly/2KKAkHO  sendHttpRequest() : http://bit.ly/2JeiYgX  checkHandshakeResponse() : http://bit.ly/2zsim7O => Create “NetworkStream (http://bit.ly/2L3q5xE)” for afterward R/W operation ■ WebSocket Send() Implementation: – Send() API : http://bit.ly/2LaYY0I  send(Opcode opcode, Stream stream, bool compressed) : http://bit.ly/2N31aYq  send(Fin fin, Opcode opcode, byte[] data, bool compressed) : http://bit.ly/2KPszQQ  sendBytes(byte[] bytes) : http://bit.ly/2zoQCkx => Wrap input into a lot of “WebSocketFrame (http://bit.ly/2N5zfHh)” then write to stream
  • 9. ■ WebSocket OnMessage event Implementation: – EventHandler<MessageEventArgs> OnMessage : ■ There’re two place emit the event: – messagec(MessageEventArgs e) : http://bit.ly/2L7etGO ■ This is binding to Action<> _message field, which is invoked On: – open() : http://bit.ly/2uaCGpl ■ Being called at Connect() API : http://bit.ly/2L65rgE – message() : http://bit.ly/2KMUt00 – startReceiving() : http://bit.ly/2NEcATw – open() : http://bit.ly/2zssHAE => Get data from internal _messageEventQueue.Dequeue() then invoke the event.
  • 10. ASP.NET Core Websocket Server ■ The whole implementation across many “Nuget Packges (https://www.nuget.org/packages)”: – Microsoft.AspNetCore.Websockets – Microsoft.AspNetCore.Http.Abstractions – Microsoft.AspNetCore.Http – Microsoft.AspNetCore.Http.Extensions – Microsoft.AspNetCore.Http.Features – Microsoft.AspNetCore.Server.Kestrel – Microsoft.AspNetCore.Server.Kestrel.Core – System.Net.WebSockets.WebSocketProtocol – System.Net.WebSockets ■ It’s impossible to get through whole source code simply by human 👀!!! ■ We have to “experiment it” with debuggable source code or being able to logging detail information.
  • 11. Build ASP.Net Core Framework Package (make it debuggable)■ Build debuggable ASP.NET Core nuget packages? 1. Clone the official build repo: Universe https://github.com/aspnet/Universe 2. Build it…...since ASP.NET Core module’s source has almost unified folder structure convention: ■ src: The real source code ■ test: Testing code ■ sample: sample project or test to verify production source ■ build: build configuration files ■ Write a example project to use those debuggable packages then run it, dive into….
  • 13. Build ASP.Net Core Framework Package ■ To build individual packages: 1. In Windows machine, Install chocolatey, git for windows, Visual Studio 2017 and ASP.NET workload, node.js (for npm): https://github.com/aspnet/Universe/wiki/Setting-a-machine-up-to-run-Universe 2. Clone Universe repo with correct tag ( -b 2.1.1), be sure to use --recursive to get associated git submodule repo in modules folder. 3. Run build.cmd (build.sh) on top folder to let ASP.NET Core Buildtools setup correct config files on first time, even if not all module can successful build. 4. Make sure the residue build process are all killed. 5. Switch to the module folder you want to build, delete anything in artifactsbuild subfolder, then use: build.cmd /p:CompileOnly=true /p:SkipTests=true To build those Nuget packages of the module, Resulting files will reside in module folder's artifactsbuild folder, and by default, they are debuggable.
  • 14. Build ASP.Net Core Framework Package (make it debuggable)■ Use “find –iname“ or “dir /s” to find Nuget packages real source location in Universe repo: ■ Exception: Microsoft.AspNetCore.Server.Kestrel Microsoft.AspNetCore.Server.Kestrel.Core is in modulesKestrelHttpServer folder ■ But the System.Net.WebSockets.WebSocketProtocol System.Net.WebSockets packages are .NET Core runtime’s built-in libraries, that belongs to the “CoreFx (https://github.com/dotnet/corefx)” repo, not in ASP.NET Core
  • 15. Time Savior: SourceLink support in VisualStudio (https://github.com/dotnet/sourcelink ) ■ Visual Studio 2017 v15.7 and above support SourceLink ( https://docs.microsoft.com/en- us/visualstudio/releasenotes/vs2017- relnotes#debug) , ■ Begin from ASP.NET Core 2.0 it support SourceLink too: https://github.com/dotnet/core/issues/897, but some packages may not ready: https://github.com/dotnet/buildtools/issues/ 1896 ■ Most of time it just works 👍
  • 16. ■ Caveat: – Can not use “GoToDefinition(F12)” if it hasn’t been using debugger dive into it. – If source code already disappear on GitHub, it cannot work. – Some too deep function(s) may not work (may be bug?!)
  • 17. Example experiment project ■ Example source repo: http://bit.ly/2KO3B4n ■ It use .NET Core SCD deployment (http://bit.ly/2maxCgj)to let ASP.NET core runtime use debuggable Nuget packages we created. ■ Runs only on Win10-x64 machine.
  • 19. Some interesting digging result: (1) ■ WebSocket connection setup is implmented in “DefaultWebSocketManager”, its AccetpWebSocketAsync() is forwarding Websocket upgrade connection work to WebSocketMiddleware: http://bit.ly/2ukREs1 ■ WebSocket SHA-1 encrypt key is hard-coded: http://bit.ly/2N2oTYT
  • 20. Some interesting digging result: (2) ■ The real “Connection Upgrade” phase is done in Microsoft.AspNetCore.Server.Kestrel nuget package’s code, which is Web Server itself: http://bit.ly/2umVGjz ■ And the WebSocket(http://bit.ly/2KO5uhK) instance is created from websocket middleware using “HttpResponseStream” as source, the real class is “ManagedWebSocket”, an internal un-documented Class:
  • 21. Some interesting digging result: (3) ■ The Actual ReadAsync() & WriteAsync() implementation entry point is extension methods: http://bit.ly/2uo2ZaL ■ Write data to websocket’s final operations is call HttpUpgradeStream’s WriteAsync(), which is also located in Web Server itself (the Microsoft.AspNetCore.Server.Kestrel.Core Nuget package) : http://bit.ly/2uaKk33 ■ Closing websocket implementation is done by ManagedWebSocket class itself: http://bit.ly/2mbw9pW
  • 24. Conclusion ■ ASP.NET Core use many Abstract class and Interface in its API, and the real implementation is DefaultOOXX most of the time. Ex: WebSocketManager  DefaultWebSocketManager HttpContext  DefaultHttpContext ■ ASP.NET Core’s Middleware is binding via “Microsoft.AspNetCore.Http.Features” Nuget’s code.
  • 25. Resources & Tools: ■ SourceGrpah: https://sourcegraph.com/ ■ VSCode & OmniSharp extension: https://code.visualstudio.com/Docs/languages/csharp ■ MDN: – Websocket API: https://developer.mozilla.org/en- US/docs/Web/API/Websockets_API – Writing WebSocket servers: https://developer.mozilla.org/en- US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers