sta / websocket-sharp Goto Github PK
View Code? Open in Web Editor NEWA C# implementation of the WebSocket protocol client and server
Home Page: http://sta.github.io/websocket-sharp
License: MIT License
A C# implementation of the WebSocket protocol client and server
Home Page: http://sta.github.io/websocket-sharp
License: MIT License
Hello, the nuget package is nice but it's a pre-release version.
So, if you want to use websocket-sharp as a dependency, your nuget package should also be a pre-release version.
Is it possible to update it ? I saw on the Unity asset store that the current version is the 1.0.6.
Thanks :-)
Hi,
Are there any plans to support HTTP redirect on the WebSocket client side as defined in the RFC?
Thanks,
Just to make his clearer..
is it necessary to own unity pro in order to use the unity asset, or will it work with unity free?
Adding this to the unity assetstore description may be helpful for people looking for a websockets asset in unity.
thank you
I receive the following error when using websocket-sharp in Unity3d 4.2:
websocket-sharp/Net/EndPointListener.cs(140,46): error CS0200: Property or indexer `System.Security.Cryptography.X509Certificates.X509Certificate2.PrivateKey' cannot be assigned to (it is read only)
Is there a workaround for this?
I'm trying to get a websocket server set up that runs on port 7031 and uses SSL. However, whenever I try to open a connection with the server it doesn't work, and the log file has this information:
4/7/2014 8:25:39 PM|Fatal|<>c__DisplayClass3.<acceptRequestAsync>b__2:479|WebSocketSharp.WebSocketException: An exception has occurred while receiving a handshake. ---> System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: value:-1 char:
at WebSocketSharp.Ext.EqualsWith(Int32 value, Char c, Action`1 action) in c:\Sources\websocket-sharp\websocket-sharp\Ext.cs:line 444
at WebSocketSharp.WsStream.readHandshakeHeaders(Stream stream) in c:\Sources\websocket-sharp\websocket-sharp\WsStream.cs:line 121
at WebSocketSharp.WsStream.ReadHandshake[T](Func`2 parser, Int32 millisecondsTimeout) in c:\Sources\websocket-sharp\websocket-sharp\WsStream.cs:line 202
--- End of inner exception stack trace ---
at WebSocketSharp.WsStream.ReadHandshake[T](Func`2 parser, Int32 millisecondsTimeout) in c:\Sources\websocket-sharp\websocket-sharp\WsStream.cs:line 225
at WebSocketSharp.Net.WebSockets.TcpListenerWebSocketContext..ctor(TcpClient client, X509Certificate cert, Boolean secure, Logger logger) in c:\Sources\websocket-sharp\websocket-sharp\Net\WebSockets\TcpListenerWebSocketContext.cs:line 67
at WebSocketSharp.Ext.GetWebSocketContext(TcpClient client, X509Certificate cert, Boolean secure, Logger logger) in c:\Sources\websocket-sharp\websocket-sharp\Ext.cs:line 515
at WebSocketSharp.Server.WebSocketServer.<>c__DisplayClass3.<acceptRequestAsync>b__2(Object state) in c:\Sources\websocket-sharp\websocket-sharp\Server\WebSocketServer.cs:line 479
I amended the function EqualsWith to show the int and char passed in so that is where the -1 comes from on the second line. I'm starting the server the following way:
_secureListener = new WebSocketServer(7031, true);
var certLocation = Path.Combine(Path.GetDirectoryName(
new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath), "server.pfx");
_secureListener.Certificate = new X509Certificate2(certLocation, "password");
_secureListener.AddWebSocketService<Listener>("/");
_secureListener.Log.File = Path.Combine(Path.GetDirectoryName(
new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath), "websocketlog.txt");
_secureListener.Start();
The certificate being used was created the following way:
makecert.exe -r -pe -n "CN=localhost" -sky exchange -sv server.pvk server.cer
pvk2pfx -pvk server.pvk -spc server.cer -pfx server.pfx
When I connect from my application's corresponding browser extensions (Chrome & Firefox) the connection is immediately closed with the status code 1006.
Any ideas what could be going wrong?
Hi,
The websocket-sharp library seems to work fine when building for standalone and android targets but it fails when running on iOS (both on the iOS device and the UnityEditor). The following is the error message on the device:
FATAL|WebSocket.processException|WebSocketSharp.WebSocketException: The header part of a frame cannot be read from the data source.
at WebSocketSharp.WsFrame+<ParseAsync>c__AnonStorey14.<>m__21 (System.Byte[] header) [0x00000] in <filename unknown>:0
at WebSocketSharp.Ext+<ReadBytesAsync>c__AnonStorey5.<>m__D (IAsyncResult ar) [0x00000] in <filename unknown>:0
It seems to be failing at WsFrame.cs:650 where the header isn't being stored and parsed properly. I've spent some time trying to debug this but couldn't find the solution. Is there a workaround or a fix for this? Thanks!
Hi,
It would be great if you can remove the integrated HTTP Server, or at least make it pluggable. When working with the server as a service, the HTTP server it is really not needed.
hi,
is there a way to run webserver with SSL? i only saw how to run standalone websocket with SSL.
EDIT: Nvm, i was using old version, so close this please.
Is there any reason known why websocket-sharp will not work over a tunnel using ssh and remote port forward.
I've been testing with SSH.NET.
If I use the standard .NET HttpListener all works fine. As soon as I use with websocket-sharp it stops working.
The issue seems very strange and I am having trouble getting any useful debug information.
I think it could either be...
Debugging and it seems that SSH.NET and the fowarding all connects correctly, which made me think it was something to do with the HttpListener - but this never gets.
Hi,
ive got a problem with:
internal void AddConnection (HttpConnection connection)
{
_connections[connection] = connection;
}
it throws index out of range very often :/
second problem is with HttpListenerRequest.cs in line 688
i need to use _method = parts [0].Replace("\0",""); to make it work, because when i try to make connection parts[0] got in text GE\0\0\0...\0T
Good Morning STA!
I'm getting the following exception after approx 60 seconds of my client running:
09.05.2014 15:08:28|Fatal|WebSocket.acceptException|WebSocketSharp.WebSocketException: The header part of a frame cannot be read from the data source.
at WebSocketSharp.WsFrame.<>c__DisplayClasse.<ParseAsync>b__d(Byte[] header)
at WebSocketSharp.Ext.<>c__DisplayClass6.<ReadBytesAsync>b__5(IAsyncResult ar)
09.05.2014 15:08:28|Fatal|WebSocket.acceptException|System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
at WebSocketSharp.Ext.<>c__DisplayClass6.<ReadBytesAsync>b__5(IAsyncResult ar)
Service.cs:56 [ERROR] Client: An exception has occurred while receiving a message.
--------------------------------------------------------------------------------------
09.05.2014 15:08:42|Fatal|WebSocket.acceptException|System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
at WebSocketSharp.Ext.<>c__DisplayClass6.<ReadBytes
Async>b__5(IAsyncResult ar)
09.05.2014 15:08:42|Fatal|WebSocket.acceptException|WebSocketSharp.WebSocketException: The header part of a frame cannot be read from the data source.
at WebSocketSharp.WsFrame.<>c__DisplayClasse.<ParseAsync>b__d(Byte[] header)
at WebSocketSharp.Ext.<>c__DisplayClass6.<ReadBytesAsync>b__5(IAsyncResult ar)
GameEngine.cs:372 [GAME] per used Per
Service.cs:61 [GAME] Client: 127.0.0.1:1542 disconnected. Reason:
Client: 127.0.0.1:1542 disconnected. Reason: 09.05.2014 15:18:23|Fatal|WebSocket.acceptException|System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
at WebSocketSharp.Ext.<>c__DisplayClass6.<ReadBytesAsync>b__5(IAsyncResult ar)
Service.cs:56 [ERROR] Client: An exception has occurred while receiving a message.
09.05.2014 15:18:24|Fatal|WebSocket.acceptException|System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine
at System.Net.Sockets.Socket.BeginReceive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, AsyncCallback callback,Object state)
at System.Net.Sockets.NetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
at WebSocketSharp.Ext.ReadBytesAsync(Stream stream,Int32 length, Action`1 completed, Action`1 error)
at WebSocketSharp.WsFrame.ParseAsync(Stream stream,Boolean unmask, Action`1 completed, Action`1 error)
at WebSocketSharp.WsStream.ReadFrameAsync(Action`1completed, Action`1 error)
at WebSocketSharp.WebSocket.<>c__DisplayClass18.<startReceiving>b__15()
at WebSocketSharp.WebSocket.<>c__DisplayClass18.<startReceiving>b__16(WsFrame frame)
at WebSocketSharp.WsFrame.<>c__DisplayClasse.<ParseAsync>b__d(Byte[] header)
at WebSocketSharp.Ext.<>c__DisplayClass6.<ReadBytesAsync>b__5(IAsyncResult ar)
Service.cs:56 [ERROR] Client: The WebSocket connection has already been closed.
I'm connecting with the collowing code
Stopwatch watch = new Stopwatch();
watch.Start();
ws = new WebSocket("ws://localhost:8140/game");
ws.OnMessage += (sender, e) =>
this.Progress(e);
ws.OnError += (sender, e) =>
Console.WriteLine("Stopwatch: " + watch.ElapsedMilliseconds);
ws.OnClose += (sender, e) =>
Console.WriteLine("Stopwatch: " + watch.ElapsedMilliseconds);
ws.Connect();
this.Login(hash);
And my server looks like this:
GameEngine gameEngine = new GameEngine();
ChatEngine chatEngine = new ChatEngine();
wssv.AddWebSocketService<GameService>("/game", () => new GameService(gameEngine));
wssv.AddWebSocketService<ChatService>("/chat", () => new ChatService(chatEngine));
wssv.AddWebSocketService<AdminService>("/admin", () => new AdminService(gameEngine, chatEngine));
wssv.Log.Level = LogLevel.Fatal;
wssv.Start();
Console.ReadKey(true);
wssv.Stop();
I logged duration of the connection three times, and i got the following timings:
57835ms First run
56207ms Second run
57343ms Third run
I'm not sure if this is something with websocket-sharp, but maybe you know the problem? 👍
When trying to compile in Visual Studio 2012, I get the following error:
Error 3 Use of unassigned local variable 'frame' websocket-sharp\WsFrame.cs 336
I just updated mono to 3.2.8 (Ubuntu 14.04 LTS)
I have this piece of code:
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
using System.Security.Cryptography.X509Certificates;
namespace Example
{
public class Laputa : WebSocketService
{
protected override void OnMessage (MessageEventArgs e)
{
var msg = e.Data == "BALUS"
? "I've been balused already..."
: "I'm not available now.";
Send (msg);
}
//protected override void OnMessage
}
public class MainClass
{
public static void Main (string [] args)
{
string url = "wss://localhost:8182";
var wssv = new WebSocketServer (url);
wssv.AddWebSocketService<Laputa> ("/Laputa");
wssv.Certificate = new X509Certificate2 ("/home/wss.pfx", "CertPass");
url = "ws://localhost:8181";
var ws = new WebSocketServer (url);
ws.AddWebSocketService<Laputa> ("/Laputa");
wssv.Start ();
ws.Start ();
Console.WriteLine ("Servers started... ");
Console.ReadKey (true);
wssv.Stop ();
ws.Stop ();
}
}
}
When i try to use ssl connection I got this:
c__AnonStorey0.<>m__0:487|System.IO.IOException: The authentication or decryption has failed. ---> System.NotSupportedException: Unsupported security protocol type
at Mono.Security.Protocol.Tls.Context.DecodeProtocolCode (Int16 code) [0x00024] in /opt/mono-3.x/mono-3.2.8/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/Context.cs:419
at Mono.Security.Protocol.Tls.Handshake.Server.TlsClientHello.processProtocol (Int16 protocol) [0x00000] in /opt/mono-3.x/mono-3.2.8/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientHello.cs:109
at Mono.Security.Protocol.Tls.Handshake.Server.TlsClientHello.ProcessAsTls1 () [0x00000] in /opt/mono-3.x/mono-3.2.8/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Server/TlsClientHello.cs:76
at Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process () [0x00037] in /opt/mono-3.x/mono-3.2.8/mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake/HandshakeMessage.cs:105
at (wrapper remoting-invoke-with-check) Mono.Security.Protocol.Tls.Handshake.HandshakeMessage:Process ()
at Mono.Security.Protocol.Tls.ServerRecordProtocol.ProcessHandshakeMessage (Mono.Security.Protocol.Tls.TlsStream handMsg) [0x0002a] in /opt/mono-3.x/mono-3.2.8/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ServerRecordProtocol.cs:74
at Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult) [0x00123] in /opt/mono-3.x/mono-3.2.8/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs:397
--- End of inner exception stack trace ---
at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x00044] in /opt/mono-3.x/mono-3.2.8/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslStreamBase.cs:111
Firefox still works with this exception. But Chrome cannot handle it. How to fix this issue?
The library is working fine in the Editor (purchased through Asset store), but I'm getting this when I build for iOS:
Cross compilation job websocket-sharp.dll failed.
UnityEngine.UnityException: Failed AOT cross compiler: /Applications/Unity/Unity.app/Contents/BuildTargetTools/iPhonePlayer/mono-xcompiler --aot=full,asmonly,nodebug,ficall,static,outfile="websocket-sharp.dll.s" "websocket-sharp.dll" current dir : Temp/StagingArea/Data/Managed
result file exists: True
stdout:
stderr:
at UnityEditor.MonoProcessUtility.RunMonoProcess (System.Diagnostics.Process process, System.String name, System.String resultingFile) [0x00000] in :0
at UnityEditor.MonoCrossCompile.CrossCompileAOT (BuildTarget target, System.String crossCompilerAbsolutePath, System.String assembliesAbsoluteDirectory, CrossCompileOptions crossCompileOptions, System.String input, System.String output, System.String additionalOptions) [0x00000] in :0
at UnityEditor.MonoCrossCompile+JobCompileAOT.ThreadPoolCallback (System.Object threadContext) [0x00000] in :0
UnityEditor.BuildPlayerWindow:BuildPlayerAndRun()
https://github.com/sta/websocket-sharp/blob/master/websocket-sharp/WebSocket.cs#L1008-L1016
Out of curiosity, why catch all exceptions after emitting the OnError event? What if someone wanted to re-throw another exception up the stack? I'm having trouble a good pattern to detect a connection failure for example... How do I notify my UI that something is wrong so that a re-connect can be initiated?
The body in the 401 response is not read which makes the authentication to fail, I get the exception ("No colon found.", "header").
If I read the body after the header in the method WsStream::ReadHandshake then it works fine.
if (_innerStream.ReadByte().EqualsWith('\r', add) &&
_innerStream.ReadByte().EqualsWith('\n', add) &&
_innerStream.ReadByte().EqualsWith('\r', add) &&
_innerStream.ReadByte().EqualsWith('\n', add))
{
string tempRes = Encoding.UTF8.GetString(buffer.ToArray());
var clStartIndex = tempRes.IndexOf("Content-Length:");
if (-1 != clStartIndex)
{
clStartIndex += ("Content-Length:".Length + 1);
int crIndex = tempRes.IndexOf('\r', clStartIndex);
string contentLenStr = tempRes.Substring(clStartIndex, crIndex - clStartIndex);
int contentLen = Convert.ToInt32(contentLenStr);
for (int i = 0; i < contentLen; ++i)
{
_innerStream.ReadByte();
}
}
read = true;
break;
}
I tested websocket-sharp (console sample) on a cloud server. Instead of the server sending back a single Send data in the onMessage, I put it inside a for loop 0 to 500 to simulate sending of records from a database. With this test, there is a disconnection error somewhere between 200 to 300 successfully received messages.
I am getting the following exception when using the latest master developing iOS app on Unity platform. This issue only happens on iOS devices (not on simulator). After some testing, the problem may be due to the some changes after the commit a5e6e6e. I suspect that is the change from Action<Opcode, byte []> to Func. This seems to be critical because this library does not work on iOS platform anymore.
ExecutionEngineException: Attempting to JIT compile method '(wrapper delegate-begin-invoke) System.Func`3<WebSocketSharp.Opcode, byte[], bool>:begin_invoke_IAsyncResult__this___Opcode_byte[]_AsyncCallback_object (WebSocketSharp.Opcode,byte[],System.AsyncCallback,object)' while running with --aot-only.
at WebSocketSharp.WebSocket.send (Opcode opcode, System.Byte[] data, System.Action`1 completed) [0x00043] in Assets/Scripts/3rdParty/WebSocket-sharp/WebSocket.cs:1105
at WebSocketSharp.WebSocket.Send (System.String data, System.Action`1 completed) [0x00054] in Assets/Scripts/3rdParty/WebSocket-sharp/WebSocket.cs:1728
at WebSocketSharp.WebSocket.Send (System.String data) [0x00000] in Assets/Scripts/3rdParty/WebSocket-sharp/WebSocket.cs:1633
at WebSocketClient.SendMessage (System.String payload) [0x00000] in Assets/Scripts/API/Network/WebSocketClient.cs:67
I just cloned the project, fired up VS 2008, and immediately I see a compilation error:
Error 1 Use of unassigned local variable 'callback' D:\git\websocket-sharp\websocket-sharp\WebSocket.cs 1106 29 websocket-sharp
AsyncCallback callback = (ar) =>
{
act.EndInvoke(ar);
if (_readyState == WsState.OPEN)
{
act.BeginInvoke(callback, null);
}
else
{
_autoEvent.Set();
}
};
In the project settings I see the project is set to use .NET 3.5.
I find this code difficult to read. It creates a lambda expression, assigns it to callback and then attempts to use callback within the scope of callback. If this did compile it looks like unbounded recursion. I admit I haven't taken the time to appreciate the full 'elegance' of this code, but it doesn't compile...
I try to receive a PDF File as a Base64 encoded String to the Websocket Client.
With a File about 1 Kb in size, it´s receiving correctly.
If i try a file with a size of i.e. 10 kb, it doesn´t receiving the Message correctly.
The Error Occours in file WsFrame.cs in method readPayloadData in Line 238/239:
if (buffer == null)
throw new IOException();
I Don´t know why the Buffer is null at this time :-(
I am able to connect to my Websocket-Sharp server just fine with Firefox Version 28.0, but as soon as I try to connect using Google Chrome Version 34.0.1847.131 m, I get the following error:
27.04.2014 13:13:27|Fatal|WebSocket.acceptException|WebSocketSharp.WebSocketException: The header part of a frame cannot be read from the data source.
bei WebSocketSharp.WsFrame.<>c__DisplayClasse.<ParseAsync>b__d(Byte[] header)
bei WebSocketSharp.Ext.<>c__DisplayClass6.<ReadBytesAsync>b__5(IAsyncResult ar)
The error appears both when using the NuGet version and a self compiled version directly taking from Github (latest commit 16f5c03).
Server initialization code:
int port = 7777;
Log.Info("Starting server socket at port " + port + "...");
this.WebSocketServer = new WebSocketSharp.Server.WebSocketServer(port);
this.WebSocketServer.AddWebSocketService<GameWebService>("/game");
// TODO: Register additional services
this.WebSocketServer.Start();
Service code:
internal sealed class GameWebService : WebSocketSharp.Server.WebSocketService
{
private static log4net.ILog Log = log4net.LogManager.GetLogger(typeof(GameWebService));
protected override void OnOpen()
{
Log.Info("Open");
}
protected override void OnClose(WebSocketSharp.CloseEventArgs e)
{
Log.Info("Closed");
}
protected override void OnError(WebSocketSharp.ErrorEventArgs e)
{
Log.Error(e.Message);
}
protected override void OnMessage(WebSocketSharp.MessageEventArgs e)
{
Log.Info(e.Data);
}
}
Client connect:
var serverUrl = 'ws://myserveraddress:7777/game';
self.connection = new WebSocket(serverUrl, ['soap']);
self.connection.onerror = self.handleConnectionError;
self.connection.onmessage = self.handleConnectionMessage;
self.connection.onopen = self.handleConnectionOpen;
self.connection.onclose = self.handleConnectionClose;
The log shows the "Open" entry logged in the OnOpen
method. Then the error occurs.
The client side JavaScript has a method attached to the onopen
event, but does not yet send any messages (e.g. the method is empty).
The website and server are not using SSL. The error happens when connectin locally or via a remote machine over the internet.
The server uses .NET 4.5
I guess this is up to interpretation of 10.3 of RFC6455
http://tools.ietf.org/html/rfc6455#section-10.3
"Clients MUST choose a new masking key for each frame"
But it appears many endpoints will close a connection if a client frame doesn't have the masking bit set. WsFrame constructor turns off the mask bit if the payload length is 0. This is most obvious with the ping functionality.
Is it possible to get this thing talking to a node.js server running WS-WebSocket ( https://github.com/einaros/ws ).
I have a service running ws, and I'm trying to get my Unity app to talk to it, and although it reports "connected", the server doesn't seem to see it.
Hi!
I have a C# Console application that serves as my server.
My unity game serves as the client ( and has your plugin embedded ).
However it seems like I never can connect to my server.
I tried your code you posted @ Issue #35 and I get the following output:
Open Socket: CONNECTING
Websocket Alive: False
WebSocket-> Error: An exception has occured while connecting.
Open socket-> OnError: CONNECTING
WebSocket-> Close-code: 1006
Websocket-> Close-reason: An exception has occured while connecting
Open Socket -> OnClose: CLOSED
WebSocket-> Error: The WebSocket connection has already been closed.
Open Socket -> OnError: CLOSED
WebSocket-> Error: The WebSocket connection has already been closed.
. . .
Open Socket -> OnError: CLOSED
WebSocket-> Error: The WebSocket connection has already been closed.
. . .
Any idea what the problem is?
Note that when i make another C# console application as a client, and have similar code in it, that it does work. So it only doesn't work when using it from within unity...
Parameter name: value
at WebSocketSharp.Ext.EqualsWith (Int32 value, Char c, System.Action`1 action) [0x00000] in <filename unknown>:0
at WebSocketSharp.WebSocketStream.readHandshakeHeaders (System.IO.Stream stream) [0x00000] in <filename unknown>:0
at WebSocketSharp.WebSocketStream.ReadHandshake[HandshakeRequest] (System.Func`2 parser, Int32 millisecondsTimeout) [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at WebSocketSharp.WebSocketStream.ReadHandshake[HandshakeRequest] (System.Func`2 parser, Int32 millisecondsTimeout) [0x00000] in <filename unknown>:0
at WebSocketSharp.Net.WebSockets.TcpListenerWebSocketContext..ctor (System.Net.Sockets.TcpClient client, System.String protocol, Boolean secure, System.Se
curity.Cryptography.X509Certificates.X509Certificate cert, WebSocketSharp.Logger logger) [0x00000] in <filename unknown>:0
at WebSocketSharp.Ext.GetWebSocketContext (System.Net.Sockets.TcpClient client, System.String protocol, Boolean secure, System.Security.Cryptography.X509C
ertificates.X509Certificate cert, WebSocketSharp.Logger logger) [0x00000] in <filename unknown>:0
at WebSocketSharp.Server.WebSocketServer+<acceptRequestAsync>c__AnonStorey0.<>m__0 (System.Object state) [0x00000] in <filename unknown>:0
6/4/2014 9:37:33 PM|Fatal|<acceptRequestAsync>c__AnonStorey0.<>m__0:0|WebSocketSharp.WebSocketException: An exception has occurred while receiving a handshake. ---> System.ArgumentOu
tOfRangeException: Argument is out of range.
I am using a web server and websocket server.
Exception occurred, which I can not catch:
unhandled Exception System.UriFormatException: A relative URI cannot be created because the 'uriString' parameter represents an absolute URI.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at WebSocketSharp.Ext.ToUri(String uriString)
at WebSocketSharp.Net.HttpListenerRequest.FinishInitialization()
at WebSocketSharp.Net.HttpConnection.onRead(IAsyncResult asyncResult)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
Self build websocket-sharp, and add dll (Assets/Plugins). And Unity Editor freeze.
using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using WebSocketSharp;
public class NewBehaviourScript : MonoBehaviour {
void Start () {
using (WebSocket ws = new WebSocket ("ws://localhost:8080")) {
print ("Open socket: "+ ws.ReadyState);
print ("Websocket Alive: "+ ws.IsAlive);
ws.OnMessage += (sender, e) => {
print("From srv:" + e.Data);
};
ws.OnOpen += (sender, e) => {
print("WebSocket-> Open:");
print ("Open socket-> OnOpen: "+ ws.ReadyState);
};
ws.OnError += (sender, e) => {
print("WebSocket-> Error:"+ e.Message);
print ("Open socket-> OnError: "+ ws.ReadyState);
};
ws.OnClose += (sender, e) => {
print("WebSocket-> Close-code:"+ e.Code);
print("WebSocket-> Close-reason:"+ e.Reason);
print ("Open socket-> OnClose: "+ ws.ReadyState);
};
ws.Connect ();
}
}
Cowboy: https://github.com/extend/cowboy
What version of WebSocket does websocket-sharp support?
websocket-sharp does work with Netty: https://github.com/netty/netty
It would be great if websocket-sharp was able to be configured for proxy traversal (using HTTP CONNECT), and support proxy basic authentication as well.
(Not sure if this is the right place for enhancement requests...)
Hi there,
I've created a application using web socket sharp. This works fine when running as a console app, however when deployed as a windows service (As Admin) it fails on send. Debugging info below.
Any ideas why this is would be most welcomed.
Many thanks
Darryl
4/07/2014 3:14:46 p.m.|Debug|WebSocket.send:0|A WebSocket connection request to wss://url:443/websocket/v2:
GET /websocket/v2 HTTP/1.1
User-Agent: websocket-sharp/1.0
Upgrade: websocket
Connection: Upgrade
Host: url:443
Sec-WebSocket-Key: pFtLpPPxJ5WBJ/G8BR5A+Q==
Sec-WebSocket-Protocol: wss
Sec-WebSocket-Version: 13
4/07/2014 3:14:46 p.m.|Debug|WebSocket.receiveHandshakeResponse:0|A response to this WebSocket connection request:
HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: kOyOtZ3xHDrgox+kybKdkG3wMZA=
Sec-WebSocket-Protocol: wss
4/07/2014 3:14:46 p.m.|Error|WebSocket.Send:0|While closing the WebSocket connection.
4/07/2014 3:14:46 p.m.|Info |WebSocket.close:0|Closing the WebSocket connection has already been done.
4/07/2014 3:14:46 p.m.|Debug|WebSocket.closeHandshake:0|Was clean?: True
sent: True received: True
I have a user UI on Android. I'm trying to set contents of text field to the value of the message received via WebSockets. The problem is that onMessage
handler is called in an another thread, while UI controls on Android are not thread-safe.
Is it possible to wrap it inside websocket-sharp
to avoid such behaviour?
I don´t know how it is in other countrys but In Germany, we have Internet-Connections with dynamic IP´s.
If we disconnect from the internet and connect again, we have an other outbound IP as the connection before.
When we don´t disconnect from the internet between 24 hours, we get a forced disconnect from the ISP.
The Result is also an other outbound IP as the connection before.
The websocket-sharp client do not register this disconnect.
After this diconnect, I got a new dynamic IP and the Websocket-Connection between Websocket-Client und Websocket-Server dows not exist anymore, because my Client got a new IP.
If I try this situation locally (Server and Client both have static IP´s), I don´t have this problems.
The Connection is down and after reconnect, the same connection is automatically used again.
I´ve tryed the same with a HTML5 Websocket client.
The result is that the HTML5 Client fired the OnClose event after a few seconds (eventually an internal timeout ?).
Do you have any ideas to resolve this problem?
Or should I take a timer that pings the server every minute to monitor the connection - and if I detect an error I make a new connection from the cient to the server?
There are some tweaks I had to make in order to get the library to build for the Unity Web Player. I'm not 100% sure how safe the changes are. Most of the issues are API calls that aren't present in the System libraries that the web player gets built with. I'm not using compression or encryption so mostly I just commented out the offending lines to satisfy the compiler.
Assets/Plugins/websocket-sharp/Ext.cs(85,81): error CS1729: The type `System.IO.Compression.DeflateStream' does not contain a constructor that takes `3' arguments
I removed the 3rd argument, also on line 119
Assets/Plugins/websocket-sharp/Net/EndPointListener.cs(172,16): error CS0200: Property or indexer `System.Security.Cryptography.X509Certificates.X509Certificate2.PrivateKey' cannot be assigned to (it is read only)
Assets/Plugins/websocket-sharp/Net/HttpConnection.cs(96,19): error CS1061: Type `WebSocketSharp.Net.Security.SslStream' does not contain a definition for `AuthenticateAsServer' and no extension method `AuthenticateAsServer' of type `WebSocketSharp.Net.Security.SslStream' could be found (are you missing a using directive or an assembly reference?)
Assets/Plugins/websocket-sharp/Net/HttpListenerRequest.cs(242,37): error CS1061: Type `System.Security.Principal.IPrincipal' does not contain a definition for `Identity' and no extension method `Identity' of type `System.Security.Principal.IPrincipal' could be found (are you missing a using directive or an assembly reference?)
Assets/Plugins/websocket-sharp/Net/ListenerAsyncResult.cs(136,22): error CS0117: `System.Threading.ThreadPool' does not contain a definition for `UnsafeQueueUserWorkItem'
This I modified as per https://github.com/kaistseo/UnitySocketIO-WebSocketSharp
Assets/Plugins/websocket-sharp/Net/WebSockets/TcpListenerWebSocketContext.cs(134,39): error CS1061: Type `System.Security.Principal.IPrincipal' does not contain a definition for `Identity' and no extension method `Identity' of type `System.Security.Principal.IPrincipal' could be found (are you missing a using directive or an assembly reference?)
Assets/Plugins/websocket-sharp/Server/HttpServer.cs(676,21): error CS0117: `System.IO.File' does not contain a definition for `ReadAllBytes'
Assets/Plugins/websocket-sharp/WebSocket.cs(1897,33): error CS1061: Type `System.IO.FileInfo' does not contain a definition for `OpenRead' and no extension method `OpenRead' of type `System.IO.FileInfo' could be found (are you missing a using directive or an assembly reference?)
Assets/Plugins/websocket-sharp/WebSocket.cs(1982,38): error CS1061: Type `System.IO.FileInfo' does not contain a definition for `OpenRead' and no extension method `OpenRead' of type `System.IO.FileInfo' could be found (are you missing a using directive or an assembly reference?)
Assets/Plugins/websocket-sharp/WebSocketStream.cs(242,19): error CS1061: Type `WebSocketSharp.Net.Security.SslStream' does not contain a definition for `AuthenticateAsServer' and no extension method `AuthenticateAsServer' of type `WebSocketSharp.Net.Security.SslStream' could be found (are you missing a using directive or an assembly reference?)
I am unable to pass System.Net.CookieCollection in the WebSocket. The CookieCollection is retrieved from the REST HttpWebRequest.
On my machine (Windows 7 64-Bit, Unity 4.5.1f3), starting the Test Server and then running a new, empty scene results in a hang that I can only resolve with a force quit.
The socket server seems to be working - the echo back works, and I can start the Test Server and interact with it from another non-Unity process, but as soon as I run the Unity scene, the program becomes unresponsive.
This is with the version purchased from the Unity Asset Store.
Hello!
I'm using websocket-sharp for my server software against web-browsers like Firefox, Opera and Chrome.
In all of these browser i get the following exception when trying to close the connection
http://hastebin.com/yuputeniyi.xml
I'm closing the connection with the following line:
this.Context.WebSocket.Close(WebSocketSharp.CloseStatusCode.AWAY, "Not logged in!");
I have checked and i can confirm that the server sends Two request wheras the first request closes the connection. But should not requests that is incoming be dumped when closing the connection? Or is it intended behavior that the server is trying to process these packages when a explicit call to Close is made?
Hi there, I'm new to using web socket sharp. Why does the sweep run every 60 seconds, closing all open sockets? Thanks. Darryl
Hi,
I'm testing a client/server combo and I'm having 2 issues:
If I exit the client application, I'm getting a "Cannot access a disposed object" on the CloseHandshake method (well, really, on the SendWsFrame, when the method tries to call the WriteFrame sub-method). It seems that the innerStream is being disposed, but I'm not sure why. I already put a breakpoint on the Dispose method of the WsStream class and it is not being invoked.
Since the client doesn't correctly close the connection, the server doesn't receives any notifications about this now missing client. That's ok, but I believe there should has to be some sort of timeout on the server so, if a client doesn't reports back in a timely period, the server automatically remove that client from the active client list.
In our application, we're connecting to a server via web sockets to listen for new data. Everything works fine on the desktop builds, and the web player on windows, and on OSX with a freshly-opened browser. After a browser reload, or closing and re-opening a tab, we get errors receiving websocket messages. It looks like we're hitting a known issue with Unity and the various Async IO methods in the web player, where Async processes don't get closed properly when the player is stopped.
Here is an informative forum post describing the issue. In this case the resolution was to abandon the Async methods and spawn a separate thread manually that does blocking reads.
http://forum.unity3d.com/threads/socket-wont-stay-connected-after-reloading-webplayer.102776/
In our case specifically the exception was "An exception has occurred while receiving a message." That error was coming from ParseAsync which was throwing the exception "The header part of a frame cannot be read from the data source." because header.Length was zero. This seems to match up with the error reported above, where async reads were returning zero bytes after a reload.
As this seems to be an open and long-standing issue in Unity, would it be hard to refactor out the Async methods? I'm not sure if there's another workaround to get things working in OSX Web Player after a refresh (if you have one we're all ears).
Thanks.
If the connection is diconnect after it is etablished, the onClose event does not fire :-(
A good enhancement could be to use the BeginAsync/EndAsync methods of the stream class, and remove all the uses of the ThreadPool. That would make the system faster as it will not have to create threads to make synchronous operations asynchronous. It's a waste of resources.
This exception we have everyday after websocket-server restart
System.NullReferenceException: Object reference not set to an instance of an object
at WebSocketSharp.WebSocket.Ping (System.Byte[] frame, Int32 timeout) [0x00000] in <filename unknown>:0
at WebSocketSharp.WebSocket.Ping () [0x00000] in <filename unknown>:0
at WebSocketSharp.WebSocket.get_IsAlive () [0x00000] in <filename unknown>:0
at WebSocketController.Stop () [0x00000] in <filename unknown>:0
at WebSocketController.OnError (System.Object sender, WebSocketSharp.ErrorEventArgs errorEventArgs) [0x00000] in <filename unknown>:0
at (wrapper delegate-invoke) System.EventHandler`1<WebSocketSharp.ErrorEventArgs>:invoke_void__this___object_TEventArgs (object,WebSocketSharp.ErrorEventArgs)
at WebSocketSharp.Ext.Emit[ErrorEventArgs] (System.EventHandler`1 eventHandler, System.Object sender, WebSocketSharp.ErrorEventArgs e) [0x00000] in <filename unknown>:0
at WebSocketSharp.WebSocket.error (System.String message) [0x00000] in <filename unknown>:0
at WebSocketSharp.WebSocket.acceptException (System.Exception exception, System.String reason) [0x00000] in <filename unknown>:0
at WebSocketSharp.WebSocket+<>c__DisplayClass18.<startReceiving>b__17 (System.Exception ex) [0x00000] in <filename unknown>:0
at WebSocketSharp.Ext+<>c__DisplayClass6.<ReadBytesAsync>b__5 (IAsyncResult ar) [0x00000] in <filename unknown>:0
Where WebSocketController.Stop() is
if (ws != null && ws.IsAlive)
{
ws.Close(CloseStatusCode.Normal, "Shutdown");
}
I run Example 4 and attack it from my client. Then I see the message.
When this error is happen, WebSocketState is CLOSED.
I think it may be because timing problem.
I've connected 10,000 clients to my server.
Memory usage of the server process look great (about 100Mb).
After disconnecting all clients, the memory usage of the server jumps to 2GB(!) and CPU usage is at 85%.
Anyone noticed that?
Any tips on whats wrong?
hello ! Thanks your great websocket server !
I read your websocket server source code. I detect every client link to server will create a new thread. Is this way will consume much system resource? How many connections can keep?
Hi there,
Just writing to let you know of a memory leak with the HttpConnection class, and a resolution.
Backstory: I have been running some stress tests against your WebServer, and noticed a sharp memory spike when running the server on .NET, with roughly 180mb being allocated per 10,000 requests. Tests were run using Apache benchmark.
Note: This issue appears to be .net specific. with no problems running on the Mono platform.
Steps to reproduce
var s = new HttpServer(5000);
s.OnGet += (object sender, HttpRequestEventArgs e) =>
{
byte[] data = System.Text.Encoding.UTF8.GetBytes("hello world");
e.Response.OutputStream.Write(data, 0, data.Length);
};
s.Start();
# apache benchmark test
ab -c 100 -n 10000 http://[ip]:5000/
The problem appears to be due to a timer inside the HttpConnection not being disposed. Additionally, its also not being disposed in the latest Mono repo also, so possibly a bug? Anyway, by dropping in a timer.Dispose() at the end of the HttpConnection.Close() method should resolve the issue.
// /websocket-sharp/Net/HttpConnection.cs line 387
internal void Close (bool force)
{
if (_socket != null) {
if (_outputStream != null) {
_outputStream.Close ();
_outputStream = null;
}
var req = _context.Request;
var res = _context.Response;
force |= !req.KeepAlive;
if (!force)
force = res.Headers ["Connection"] == "close";
if (!force &&
req.FlushInput () &&
(!_chunked || (_chunked && !res.ForceCloseChunked))) {
// Don't close. Keep working.
_reuses++;
unbind ();
init ();
BeginReadRequest ();
return;
}
var socket = _socket;
_socket = null;
try {
socket.Shutdown (SocketShutdown.Both);
}
catch {
}
finally {
if (socket != null)
socket.Close ();
}
unbind ();
removeConnection ();
//--------------------------
// dispose of timer
//-------------------------
try {
_timer.Dispose()
}
catch {
}
return;
}
}
Cheers
Tomcat 7 comes with several websocket examples that can be compiled and deployed locally (see here http://tomcat.apache.org/tomcat-7.0-doc/web-socket-howto.html). Here's a link to the latest source example (http://apache.mirrors.hoobly.com/tomcat/tomcat-7/v7.0.37/src/apache-tomcat-7.0.37-src.zip) and I can send an eclipse project if you want to try it out locally.
Anyway, I can use their chat program in a browser, but whenever I try to connect in C# using websocket-sharp, I am able to connect, and can send messages, but cannot receive them.
When I receive messages, the function
AsyncCallback callback = (ar) =>
{
WsFrame frame;
try
{
var readLen = stream.EndRead(ar);
frame = readLen == 2
? parse(header, stream, unmask)
: null;
}
catch
{
frame = null;
}
finally
{
if (!completed.IsNull())
completed(frame);
}
};
is called, but readLen=1 and not 2. When I first connect, readLen=2 and I get a welcome to the server message, but then whenever a user sends a message, I get readLen=1.
I'm assuming that apache is doing it right since my browsers can all connect to the chat client okay.
Hello. We are trying to reduce the IPA size on a game by using ByteConde Stripping but are unsure on what classes we need to include in the link.xml file to make websocket-sharp work. Any pointers would be greatly appreciated!
Thanks,
Alejandro.
I have not looked into this too much more yet, but I did a quick test where the pong is not being received from wss://echo.websocket.org on the latest master code.
We have used websocket-sharp before and it was working fine when WebSocketState was still WsState (so more than 6 months ago). So switching back to the older code does have pong being received.
Any notes or suggestions on changes that may have occurred on the implementation would be great. We are listening for Opcode.PONG in OnMessage.
WebSocket connection fails if server returns 0 for content length. The code handles the case correctly if no content length is provided but fails if the content length is 0.
This leads to a timeout. The reader seems to be waiting forever for 0 bytes.
Can be fixed in ReadHandshake or readHandshakeEntityBody (of WsStream class) by checking for 0 in content length and then not reading from socket.
Not sure in which place you would prefer to fix it.
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.