- ๐ซ How to reach me:
- Mastodon bryce
bryceg / owin.websocket Goto Github PK
View Code? Open in Web Editor NEWA library for handling OWIN WebSocket connections
License: MIT License
A library for handling OWIN WebSocket connections
License: MIT License
CommonServiceLocator has a breadking change from 2.0.1 onwards where its namespace changes from Microsoft.Practices.ServiceLocation to CommonServiceLocator.
https://github.com/unitycontainer/commonservicelocator/commit/908a30f0f4c036d1ded0c0967fa3a7ae823aa5ce
It seems to me this library does not make the change accordingly.
I am getting this msg : "The type 'IServiceLocator' is defined in an
assembly that is not referenced..."
My workaround is to downgrade CommonServiceLocator to 1.3.
Websocket Continuation Frames should be supported!
I have created a websocket using Owin.Websocket.WebSocketConnection to receive messages from my Frontend.
public class MyWebScoket : WebSocketConnection
{
protected MyWebScoket(int maxMessageSize = 65536) : base(maxMessageSize)
{
//logic
}
public override void OnClose(WebSocketCloseStatus? closeStatus, string closeStatusDescription)
{
//logic
}
public override Task OnMessageReceived(ArraySegment<byte> message, WebSocketMessageType type)
{
//logic
}
public override void OnOpen()
{
//logic
}
public override void OnReceiveError(Exception error)
{
//logic
}
}
When the message size is below the set message size, CPU usage of API is normal and everything is functioning as it should, however when the message size exceeds the limit, CPU usage of API increases dramatically, causing my machine to stop responding even to mouse clicks.
This seems strange, as the message sending rate is always the same.
What is the reason of such behavior?
I added breakpoints inside all overridden methods, but none of them is reached, I thought if the message limit size is exceeded the execution should go to OnReceiveError.
I'm seeing a lot of WebSocketException
being thrown after OnClose is called. Since it's after the connection has been closed it doesn't seem to be affecting the functionality of the service but it is filling up the logs quite a lot. Is there anyway to avoid this?
System.Net.WebSockets.WebSocketException:
at System.Web.WebSockets.WebSocketPipe+<>c__DisplayClass9_0.<ReadFragmentAsync>b__0 (System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.WebSockets.AspNetWebSocket+<DoWork>d__45`1.MoveNext (System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.WebSockets.AspNetWebSocket+<>c__DisplayClass36_0+<<ReceiveAsyncImpl>b__0>d.MoveNext (System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at Owin.WebSocket.Handlers.NetWebSocket+<ReceiveMessage>d__4.MoveNext (Owin.WebSocket, Version=1.7.0.0, Culture=neutral, PublicKeyToken=null)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at Owin.WebSocket.WebSocketConnection+<RunWebSocket>d__7.MoveNext (Owin.WebSocket, Version=1.7.0.0, Culture=neutral, PublicKeyToken=null)
Hi Bryce,
First, thank you for putting together Owin.WebSocket - It's great ๐
I've noticed that the nugget spec picks up Owin.WebSocket.dll
from src\build
. However, currently only the Debug configuration outputs to that folder. It would seem that the debug version of the dll is packaged in the Nuget - is this intentional?
Your library does not use http://owin.org/spec/extensions/owin-WebSocket-Extension-v0.4.0.htm specification, therefore can not be used on generic OWIN servers (NOwin, Kestrel, etc), only on HttpListener/IIS.
Please, don't lie to users of your library and fix that.
What is the purpose of the WebSocketMessageType enum, considering that all your send methods require byte data rather than a string type? If I'm forced to convert to UTF8 bytes, that's as good as binary in my mind. When would you use the enum? When would you use the "close" value of that enum?
I would assume that all packets on a given channel have the same Content-Type and Content-Encoding headers because HTTP would only send them with the initial connection. Is that right? What do you send for those values? I would like to be able to specify that my data is deflated UTF8 JSON.
Could you please provide tagging/branching on the source repository so that it's easier to find out what are the sources exactly matching the released NuGet package version?
Or even be able to read it on Releases page.
Should I assume that package version 1.5.0 is corresponding to the current HEAD (revision 9809a18 )?
Thanks in advance.
Using chrome created a direct copy of of the reference to websockets found in the documention.
index.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div>
ServerStatus
<div id="serverStatus"></div>
Destination
<div id="destination"></div>
Server Response
<div id="serverResponse"></div>
TextMessage
<div id="textmessage"></div>
Source
<div id="source"></div>
</div>
<script>
try {
socket = new WebSocket("ws://localhost:1337/ws");
socket.onopen = function (openEvent) {
document.getElementById("serverStatus").innerHTML =
'WebSocket Status:: Socket Open';
};
socket.onmessage = function (messageEvent) {
if (messageEvent.data instanceof Blob) {
var destinationCanvas = document.getElementById('destination');
var destinationContext = destinationCanvas.getContext('2d');
var image = new Image();
image.onload = function () {
destinationContext.clearRect(0, 0,
destinationCanvas.width, destinationCanvas.height);
destinationContext.drawImage(image, 0, 0);
}
image.src = URL.createObjectURL(messageEvent.data);
} else {
document.getElementById("serverResponse").innerHTML =
'Server Reply:: ' + messageEvent.data;
}
};
socket.onerror = function (errorEvent) {
document.getElementById("serverStatus").innerHTML =
'WebSocket Status:: Error was reported';
};
socket.onclose = function (closeEvent) {
document.getElementById("serverStatus").innerHTML =
'WebSocket Status:: Socket Closed';
};
}
catch (exception) { if (window.console) console.log(exception); }
function sendTextMessage() {
if (socket.readyState != WebSocket.OPEN) return;
var e = document.getElementById("textmessage");
socket.send(e.value);
}
function sendBinaryMessage() {
if (socket.readyState != WebSocket.OPEN) return;
var sourceCanvas = document.getElementById('source');
socket.send(sourceCanvas.msToBlob());
}
</script>
</body>
</html>
Then used the following to try to bootstrap up a test.
Program.cs
using System;
using System.Diagnostics;
using System.Net.WebSockets;
using System.Threading.Tasks;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.StaticFiles;
using Owin;
using Owin.WebSocket;
using Owin.WebSocket.Extensions;
namespace WebsocketServer
{
class Program
{
const int port = 1337;
private static readonly string url = "http://localhost:\{port}";
static void Main(string[] args)
{
using (WebApp.Start<Startup>(url))
{
//StartChrome();
Console.WriteLine("Running on \{url}");
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapWebSocketRoute<MyWebSocket>("/ws");
app.UseFileServer(new FileServerOptions()
{
EnableDirectoryBrowsing = true,
FileSystem = new PhysicalFileSystem("../..")
});
}
}
public class MyWebSocket : WebSocketConnection
{
public override Task OnMessageReceived(ArraySegment<byte> message, WebSocketMessageType type)
{
//Handle the message from the client
//Example of JSON serialization with the client
// //var json = Encoding.UT8.GetString(message.Array, message.Offset, message.Count);
// //Use something like Json.Net to read the json
Debugger.Break();
return null;
}
public override void OnOpen()
{
Debugger.Break();
SendText(new byte[] { }, true);
}
//public override void OnClose(WebSocketCloseStatus closeStatus, string closeDescription){}
//public override bool Authenticate(IOwinContext requestContext){return true;}
}
}
Chrome & IE consoles are both saying WebSocket connection to 'ws://localhost:1337/ws' failed: Error during WebSocket handshake: Unexpected response code: 400
. Are there handshakes that aren't being completed properly?
Is it posible to have an example of implementation of
public override bool AuthenticateRequest(IOwinRequest request)
And how a client invokes this method
During a debugging session (where everything is slow) I could verify a situation that lead to the OnDisconnected not being ever sent.
I believe the channel should always call OnDisconnected even if the worst cases when the client cannot be reached anymore.
Also, please consider implementing IDisposable in the WebSockeConnection, exposing the overridable Dispose(bool) (as for dispose pattern) so that disposable resources in derived classes can close the lifecycle of any custom resources.
In the RFC the Sec-WebSocket-Accept
[...] is sent from the server to the client [...]
but in WebSocketConnection.cs
the server expects it from the client. That seems to be the reason why it doesn't work with websocket-sharp.
See also this question and answer on SO: http://stackoverflow.com/questions/15951774/naming-convention-for-async-methods
When using a Web Socket client (https://github.com/StefH/WebSocketTest), I can only get around 5000 web socket connections on IIS Express?
Is there a setting in web.config or in Owin.WebSocket which I need to modify ?
The assemblies coming with the NuGet package aren't signed. This means signed assemblies can't depend on them. It would be nice to have a signed version of this package out.
Error "Assembly generation failed -- Referenced assembly 'Owin.WebSocket' does not have a strong name"
Did sign it myself but figured it was worth noting.
Is per Message Compression usable with this Websocket?
Hello,
Thanks for the great library. I got it to work on self host - web API - windows, but when I deploy the self host on mono, I start receiving 400 responses for connection attempts.
Did you try that before? any clues you can help me with?
Many thanks in advance,
Yaser
WebSocket connection to 'domain/ws' failed: Error during WebSocket handshake: Unexpected response code: 403
I am trying to understand this error. It is not appearing on localhost at all, so, I think the package code is fine. It is appearing on my websocket enabled IIS stage server. I tried opening a support ticket as well as googling to no avail. If you could be so kind as to point me to some possible causes I would be so happy.
The app is an MVC 4 app.
public override bool AuthenticateRequest(IOwinRequest request)
{
//Always false,I have a login,In Controller Can See IsAuthenticated equal True
return request.Context.Request.User != null && request.Context.Request.User.Identity.IsAuthenticated;
}
Otherwise do you think to add support for it?
Thx.
Using this js cannot call OnOpen method
socket = new WebSocket("ws://x.x.x.x:ppp/ws");
socket.onopen = function (openEvent) {
document.getElementById("serverStatus").innerHTML =
'WebSocket Status:: Socket Open';
};
The constructor StatusWebSocket is called.
public StatusWebSocket()
{
UniqueId = Guid.NewGuid();
}
public override void OnOpen()
{
connections.Add(UniqueId, this);
log.DebugFormat("New websocket connected {0}, now have {1} in list", UniqueId, connections.Count);
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.