Git Product home page Git Product logo

websocket4net's Issues

Stack overflow (Silverlight 5)

WebSocket4Net is great - and thanks for continuing to support Silverlight for those of us that are stuck with it!

So far everything is working great except for a fairly regular stack overflow. Seems to happen when receiving a stream of 10Kb packets from the server?

stacktrace.txt

New version

Hey!
Is there any plan on releasing a new version through NuGet with your latest changes?

Handshake issue - the "Upgrade" header should use lowercase ("websocket")

In drafthybi00processor.cs and DraftHybi10Processor.cs, the "Upgrade" header is added using the casing "WebSocket".

The RFC 6455 standard says: "The request MUST contain an |Upgrade| header field whose value
MUST include the "websocket" keyword."

I am running into some scenarios where this casing difference is causing the handshake to not complete. If I change the case in the files above to "websocket", everything works fine.

Option to accept self signed certificateSSL certificate on Android Platform

Hi,
I downloaded your examples and running lates stable version of websocket4net. Is there a way I can achieve ServerCertificateValidationCallback to return true able to connect to server accepting wss:// connection. Will it work with TLS 1.0 since Xamarin is running few version behind to mono 4.6 which has the fix for TLS 1.2

I would appreciate if you can give a detail answer.

Things tried: #46 : Allow certificate does not help.
#40

Thanks!

Test\Test\WebSocketClientTest.cs - SessionEventHandler not found

I get this error while trying to compile test application. Couldn't find SessionEventHandler -class from project.

Error 1 The type or namespace name 'SessionEventHandler' could not be found (are you missing a using directive or an assembly reference?) ..\Test\Test\WebSocketClientTest.cs 148 54 Test

NullReferenceException when app goes to background

Hey there, when my app is sent to background, usually I get this error.

{System.Windows.ApplicationUnhandledExceptionEventArgs}
base: {System.Windows.ApplicationUnhandledExceptionEventArgs}
_exception: {System.NullReferenceException: Object reference not set to an instance of an object.
at System.Net.Sockets.Socket.ResetHandle()
at System.Net.Sockets.SocketNotificationCallback.Paused(XPauseType pauseType)
at System.Net.Sockets.SocketNotificationManager.Paused(XPauseType pauseType)
at MS.Internal.Interop.SocketNotificationCallbackProxy.Paused(XPauseType pauseType)
at MS.Internal.Interop.NotificationService.NotificationPaused(XPauseType pauseType)
at MS.Internal.FrameworkCallbacks.NotificationPaused(UInt32 pauseType)}
_handled: false
ExceptionObject: {System.NullReferenceException: Object reference not set to an instance of an object.
at System.Net.Sockets.Socket.ResetHandle()
at System.Net.Sockets.SocketNotificationCallback.Paused(XPauseType pauseType)
at System.Net.Sockets.SocketNotificationManager.Paused(XPauseType pauseType)
at MS.Internal.Interop.SocketNotificationCallbackProxy.Paused(XPauseType pauseType)
at MS.Internal.Interop.NotificationService.NotificationPaused(XPauseType pauseType)
at MS.Internal.FrameworkCallbacks.NotificationPaused(UInt32 pauseType)}
Handled: false

Here is the full stack trace:

Chat.WP8.DLL!Chat.WP8.App.Application_UnhandledException(object sender, System.Windows.ApplicationUnhandledExceptionEventArgs e) Line 155   C#
System.Windows.ni.dll!MS.Internal.Error.CallApplicationUEHandler(System.Exception e)    Unknown
System.Windows.ni.dll!MS.Internal.JoltHelper.OnUnhandledException(object sender, System.UnhandledExceptionEventArgs args)   Unknown
[Native to Managed Transition]  
System.Net.ni.dll!System.Net.Sockets.Socket.ResetHandle()   Unknown
System.Net.ni.dll!System.Net.Sockets.SocketNotificationCallback.Paused(System.Net.Sockets.XPauseType pauseType) Unknown
System.Net.ni.dll!System.Net.Sockets.SocketNotificationManager.Paused(System.Net.Sockets.XPauseType pauseType)  Unknown
System.Windows.ni.dll!MS.Internal.Interop.SocketNotificationCallbackProxy.Paused(MS.Internal.Interop.XPauseType pauseType)  Unknown
System.Windows.ni.dll!MS.Internal.Interop.NotificationService.NotificationPaused(MS.Internal.Interop.XPauseType pauseType)  Unknown
System.Windows.ni.dll!MS.Internal.FrameworkCallbacks.NotificationPaused(uint pauseType) Unknown

I've noticed you had a similar (same?) issue on CodePlex http://websocket4net.codeplex.com/discussions/436322 , but I could not comment there, as it needs a login.

Was that solved?
You asked about the thread, it's the main thread:

    3348    1   Main Thread Main Thread Chat.WP8.DLL!Chat.WP8.App.Application_UnhandledException    Normal

As there is no source code anywhere, I can't actually catch this, except on Application_UnhandledException.
Any idea?

Thanks
CodeKnox

Incorrect headers initial HTTP request

RFC 7230 states:

Since the Host field-value is critical information for handling a
request, a user agent SHOULD generate Host as the first header field
following the request-line.

In this implementation Host is the last header field. Some servers rely on the Host field coming first.

WebSocket4Net.WP80 project load failed issue

Hi kerry,

I have cloned the newest WebSocket4Net codes then double click the WebSocket4Net.WP80.sln file to run WP8Test sample, but the WebSocket4Net.WP80 project load failed in Soluiton Explorer. It also have below two warnings:
Warning 2 The referenced component 'WebSocket4Net.WP80' could not be found. WP8Test
Warning 1 The referenced project '....\WebSocket4Net.Silverlight\WebSocket4Net.WP80.csproj' does not exist. WP8Test

I use the VS 2012 and Windows Phone SDK 8.0 env. I tried to resolve this issue by modify WebSocket4Net.WP80.sln and WebSocket4Net.WP80.csproj, but after handle this issue, the emulator still can't launch.

Could you take a look, thanks very much.

Cannot send more than 4096 bytes of data and text(including frame size)

Since I wanted to send files to server over websockets, I wrote the code like this.
client code:

static void Main(string[] args)
{
    var socket=new WebSocket("ws://127.0.0.1:8000",null,WebSocketVersion.Rfc6455);
    socket.Opened+=(o,e)=>{
        Console.WriteLine("Opened");
        var data=File.ReadAllBytes("[filename]");
        socket.Send(data,0,data.Length);
    };
    socket.Closed+=(o,e)=>Console.WriteLine("Closed");
    socket.Open();
    while(Console.ReadLine()!="q");
    if(socket.State==WebSocketState.Open) socket.Close();
}

But this code didn't work expectedly.
In my research, this problem may causes when I try to send more than 4096 bytes of data.
Is this problem caused by a bug?
Please help!

WebSocket close when it send auto ping.

I use WebSocket4Net to connect "Chrome Browser" for remote debugging. I found after connect build for 1 minute, the connect will receive CLOSE event, and auto close.

By step into WebSocket4Net source code,I find once auto ping is send,the connection is closed!

I don't know why this happend. May be the reason inside Chrome,but if this project has error,I hope you know that and fix it.

Now I had to modify the interval of auto ping timer to 24 hour, to prevent connection close.

The code I modified is inside :ChromeSession.cs

    protected internal virtual void OnHandshaked()
    {
            //... ...
            //Ping auto sending interval's default value is 60 seconds
            if (AutoSendPingInterval <= 0)
                AutoSendPingInterval = 3600*24;//60 <---------- here ,modified!!!
            m_WebSocketTimer = new Timer(OnPingTimerCallback, ProtocolProcessor, AutoSendPingInterval * 1000, AutoSendPingInterval * 1000);
        }

//...
}


大侠!我英语不好,不知道你看明白了没:)

Bind to specific LocalEndPoint

How do I bind to a specific local endpoint before connecting? I see that the clientengine supports custom endpoint but it seems like the feature isn't implemented in websocket4net?

Case Sensitive Upgrade Header

Some backends do a case sensitive check on the upgrade header and will require the header to be either “upgrade” or “Upgrade”, failing on one and working on the other. Please provide an option to specify upgrade header case.

Windows Phone 8?

Hello -

Not really an issue, just a question. I'm wondering if you are planning on Windows Phone 8 support? I see you've got 7.1 support, so maybe 8 isn't far off?

Thanks for the great work and effort you put into this.

Option to ignore SSL certificate hostname mismatch

Hi all,

in my testing environment, I am required to establish a wss:// connection to a test server with a self-signed SSL certificate. The connection goes through an SSH tunnel, such that additionally the hostname in the certificate does not match the hostname in the websocket url (which is "localhost"). All this is used for a WAMP connection (see also Code-Sharp/WampSharp#131).

Now, to ignore the certificate being self-signed, I found WebSocket.AllowUnstrustedCertificate to be my friend. Is there a similar switch to ignore host mismatches? If not, would it be easy to implement?

Thanks in advance
Michael

Is it asynchronous?

Let's say I'm accepting packets from multiple machines, each packet should be responded, but the response is a bit slow... say it takes 20 seconds for each packet.

Will it still receive packets even if WebSocket_MessageReceived is blocked?

Can you help to release to NuGet

Currently, we focus on Win10 RedStone (14393) UWP development, but cannot find the package in the NuGet.
After download the source code from Github, we get failed list in the VS2015 update3.

错误 CS0103 当前上下文中不存在名称“m_SecureProtocols”
错误 Some packages are not compatible with UAP,Version=v10.0 (win10-arm).
错误 Some packages are not compatible with UAP, Version = v10.0 (win10-arm-aot).
错误 Some packages are not compatible with UAP, Version = v10.0 (win10-x64).
错误 Some packages are not compatible with UAP, Version = v10.0 (win10-x64-aot).
错误 Some packages are not compatible with UAP, Version = v10.0 (win10-x86).
错误 Some packages are not compatible with UAP, Version = v10.0 (win10-x86-aot).
错误 System.Net.Security 4.0.0 为 UAP, Version= v10.0 上的 System.Net.Security 提供了编译时引用程序集,但没有与 win10-arm 兼容的运行时程序集。
错误 System.Net.Security 4.0.0 为 UAP, Version= v10.0 上的 System.Net.Security 提供了编译时引用程序集,但没有与 win10-arm-aot 兼容的运行时程序集。
错误 System.Net.Security 4.0.0 为 UAP, Version= v10.0 上的 System.Net.Security 提供了编译时引用程序集,但没有与 win10-x64 兼容的运行时程序集。
错误 System.Net.Security 4.0.0 为 UAP, Version= v10.0 上的 System.Net.Security 提供了编译时引用程序集,但没有与 win10-x64-aot 兼容的运行时程序集。
错误 System.Net.Security 4.0.0 为 UAP, Version= v10.0 上的 System.Net.Security 提供了编译时引用程序集,但没有与 win10-x86 兼容的运行时程序集。
错误 System.Net.Security 4.0.0 为 UAP, Version= v10.0 上的 System.Net.Security 提供了编译时引用程序集,但没有与 win10-x86-aot 兼容的运行时程序集。
错误 检测到 System.Collections 的版本冲突。
WebSocket4Net.UWP (>= 1.0.0) -> SuperSocket.ClientEngine.Core (>= 0.8.0.3) -> System.Net.Sockets (>= 4.1.0) -> System.Net.Primitives (>= 4.0.11) -> runtime.win.System.Net.Primitives (>= 4.0.11) -> System.Collections (>= 4.0.11) WebSocket4Net.UWP (>= 1.0.0) -> Microsoft.NETCore.UniversalWindowsPlatform (>= 5.0.0) -> Microsoft.NETCore.Runtime (>= 1.0.0) -> Microsoft.NETCore.Runtime.CoreCLR-arm(>= 1.0.0) -> System.Collections (= 4.0.10).

Pong does not contain identical application data to ping frame being responded to

Our websocket server is sending ping frames with 8 bytes of application data to a client using WebSocket4Net.0.10. The pong frames we're getting in response do not contain the same data as the ping frames we're sending. Firefox and Chrome both respond w/ identical bytes. Here's an example of what's sent to and received from a WebSocket4Net client:

Ping bytes sent: [0 0 1 79 -36 33 -9 -117]
Pong bytes received: [0 0 1 79 -17 -65 -67 33 -17 -65 -67 -17 -65 -67]

The length of the responses varies, though we often see the same values repeated.

Here's a bit from the relevant section of RFC 6455:

A Pong frame sent in response to a Ping frame must have identical
"Application data" as found in the message body of the Ping frame
being replied to.

Is this a known issue?

Connection error if the status message in the handshake is not in English

On some servers, the HTTP status messages are not in English, but in the client's locale (based on the Accept-Language header). I noticed this on some Tomcat servers at work, but not all of them (probably based on configuration). So if the status message is in French, the response status line looks like this:

HTTP/1.1 101 Changement de Protocols

The problem is that WebSocket4Net doesn't check just the status code, but the whole response status line, so it throws an exception when it encounters the unexpected message.

The offending code is in ProtocolProcessorBase:

    protected static string[] ExptectedResponseVerbLines = new string[]
    {
        "HTTP/1.1 101 WebSocket Protocol Handshake",
        "HTTP/1.1 101 Web Socket Protocol Handshake",
        "HTTP/1.1 101 Switching Protocols"
    };

And in DraftHybi00Processor and DraftHybi10Processor (in the VerifyHandshake method):

        if (!ExptectedResponseVerbLines.Contains(verbLine))
        {
            description = verbLine;
            return false;
        }

WebSocket4Net should only check the status code, not the message. The message could contain anything, as the HTTP protocol doesn't enforce a specific text.

Unhandled NullReferenceException

I was previously able to reproduce this issue, but I have a workaround in my code that makes it less likely to occur. The use case for the exception was relatively large number of incoming MESSAGE EventType (200-300 per sec) being handled by the client. Looking at the code, this has to be some kind of race condition because the exception is occurring on a parameter (m_PreviousFrames) that was only provided from one location (DraftHybi10DataReader) and appears to be checked for null and checked to be at least the size necessary for the indexing that is required in WebSocketCommandInfo where the exception occurs. Since the only time "m_PreviousFrames" is set to null is just after the path for the crash, I'm assuming that a different frame has already started processing (and had to be non-null to even get on this path).

Looking at WebSocket.cs, it seems that in the OnDataReceived method, there is a loop used to process all "WebSocketCommandInfo" that the CommandReader has. I'm guessing with lower load, this loop breaks early and doesn't cause a problem. Also, since the "m_PreviousFrames" parameter is checked, the race condition has a very small window to occur.

Let me know if there is any more useful information that I can provide.

Here is the stacktrace:

Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.NullReferenceException
at SuperSocket.ClientEngine.Protocol.ArraySegmentList1[[System.Byte, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].CopyTo(Byte[], Int32, Int32, Int32) at WebSocket4Net.WebSocketCommandInfo..ctor(System.Collections.Generic.IList1<WebSocket4Net.Protocol.WebSocketDataFrame>)
at WebSocket4Net.Protocol.DraftHybi10DataReader.GetCommandInfo(Byte[], Int32, Int32, Int32 ByRef)
at WebSocket4Net.WebSocket.OnDataReceived(Byte[], Int32, Int32)
at WebSocket4Net.WebSocket.client_DataReceived(System.Object, SuperSocket.ClientEngine.DataEventArgs)
at SuperSocket.ClientEngine.ClientSession.OnDataReceived(Byte[], Int32, Int32)
at SuperSocket.ClientEngine.SslStreamTcpSession.OnDataRead(System.IAsyncResult)
at System.Net.LazyAsyncResult.Complete(IntPtr)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(System.Object, IntPtr)
at System.Net.Security._SslStream.ProcessFrameBody(Int32, Byte[], Int32, Int32, System.Net.AsyncProtocolRequest)
at System.Net.Security.SslStream.ReadFrameCallback(System.Net.AsyncProtocolRequest)
at System.Net.AsyncProtocolRequest.CompleteRequest(Int32)
at System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(Int32)
at System.Net.FixedSizeReader.ReadCallback(System.IAsyncResult)
at System.Net.LazyAsyncResult.Complete(IntPtr)
at System.Net.ContextAwareResult.CompleteCallback(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Net.ContextAwareResult.Complete(IntPtr)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(System.Object, IntPtr)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32, UInt32, System.Threading.NativeOverlapped
)
at System.Threading.IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped)

again "unknown server protocol version"

hi, kerryjiang

i'm trying to connect to Mt Gox using their websocket API. but Websocket4Net gives the error "unknown server protocol version", when i do WebSocket.Open().

i saw that someone else ("shlomiw") also posted this problem. he mentioned that the origin should be "Origin: http://websocket.mtgox.com" and not "Origin: websocket.mtgox.com". the rfc 6455 that you told him you were going to look at confirms this too, in its examples.

can you look into this?

i'm connecting to Mt Gox with the following code:

WebSocket ws;

public Form1() // form constructor
{
    InitializeComponent();

    ws = new WebSocket("ws://websocket.mtgox.com/mtgox");
    ws.Opened += new EventHandler(ws_opened);
    ws.MessageReceived += new EventHandler<MessageReceivedEventArgs>(ws_message);
    ws.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(ws_error);
    ws.Closed += new EventHandler(ws_closed);
}

private void btnTest_Click(object sender, EventArgs e)
{
    ws.Open();
}

private void ws_error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
{
    SetMessage("error");
}

PCL support

Is it possible to add a PCL support for WebSockets? Or is it platform dependent?

ArgumentOutOfRangeException - ParseMimeHeaders

I'm getting an error in Extensions.cs, ParseMimeHeader function, when the line variable does not contain a colon.

int pos = line.IndexOf(m_Colon); //looks for location of colon value
//line = string without a colon

Since there is no colon in the line variable, the pos equals -1 after the indexOf operation.

string key = line.Substring(0, pos); //throws exception since pos is -1

WebSocket4Net Visual Basic 2010

Hi kerry,

Now the demand, in the project I want to Visual Basic code using WebSocket4Net, the code as follows
Imports WebSocket4Net
  Dim websocket As New JsonWebSocket("ws://localhost:8168")
websocket.Open()
websocket.Send("connection", "msg")
This does not report any errors,The server has not received any messages!
Could you take a look, thanks very much.

send multiple message error

I'm using WebSocketListener for server and WebSocket4Net for client, and the application is working with a robot, if the client typing so quickly then it will show the error "無法從傳輸連接讀取資料: 遠端主機已強制關閉一個現存的連線。";

Is this kind of problems causing by library or because of the websocket couldn't send & receive at the same time?

Thanks.

SocketNotConnected exception from PING

I think this could be handled better.

I'm doing a lot of tests of network tolerance on our app and from time to time I get the below call stack on an exception. As it originates from a Ping on another thread not under my control, it just goes straight to unhandled exception.

Any way to make this better?

at SuperSocket.ClientEngine.TcpClientSession.DetectConnected()
at SuperSocket.ClientEngine.TcpClientSession.TrySend(ArraySegment1 segment) at SuperSocket.ClientEngine.ClientSession.Send(ArraySegment1 segment)
at SuperSocket.ClientEngine.ClientSession.Send(Byte[] data, Int32 offset, Int32 length)
at WebSocket4Net.Protocol.DraftHybi10Processor.SendDataFragment(WebSocket websocket, Int32 opCode, Byte[] playloadData, Int32 offset, Int32 length)
at WebSocket4Net.Protocol.DraftHybi10Processor.SendMessage(WebSocket websocket, Int32 opCode, String message)
at WebSocket4Net.Protocol.DraftHybi10Processor.SendPong(WebSocket websocket, String pong)
at WebSocket4Net.Command.Ping.ExecuteCommand(WebSocket session, WebSocketCommandInfo commandInfo)
at WebSocket4Net.WebSocket.ExecuteCommand(WebSocketCommandInfo commandInfo)
at WebSocket4Net.WebSocket.OnDataReceived(Byte[] data, Int32 offset, Int32 length)
at WebSocket4Net.WebSocket.client_DataReceived(Object sender, DataEventArgs e)
at SuperSocket.ClientEngine.ClientSession.OnDataReceived(Byte[] data, Int32 offset, Int32 length)
at SuperSocket.ClientEngine.SslStreamTcpSession.OnDataRead(IAsyncResult result)
at System.IO.Stream.ReadWriteTask.InvokeAsyncCallback(Object completedTask)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.IO.Stream.ReadWriteTask.System.Threading.Tasks.ITaskCompletionAction.Invoke(Task completingTask)
at System.Threading.Tasks.Task.FinishContinuations()
at System.Threading.Tasks.Task.FinishStageThree()
at System.Threading.Tasks.Task.FinishStageTwo()
at System.Threading.Tasks.Task.Finish(Boolean bUserDelegateExecuted)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
at System.Threading.Tasks.Task.ExecuteEntry(Boolean bPreventDoubleExecution)
at System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

get actual dota of message received

Some times my server sends compresed messages. how can i get the actual data on messagereceived?
not just e.message but i want e.message.data

thank you

Maybe a bug on JsonWebSocket Constructor

In file "WebSocket4Net/WebSocket4Net/JsonWebSocket.cs" on lines 106-107 i think you want write :

if (websocket.State != WebSocketState.None)
throw new ArgumentException("The websocket must be in the initial state.", "websocket");

Connection via proxy is not working

I'm trying to connect to websocket via a Squid proxy. I'm passing the IP address and port via the httpConnectProxy parameter of the WebSocket constructor.

If I try to connect to a ws:// URL, I get a 400 error from the proxy. With a wss:// URL, I get an SSL error ("The handshake failed due to an unexpected packet format").

The same scenarios (normal and secure connection) work fine with System.Net.WebSockets.ClientWebSocket. So I used Wireshark to compare the behavior of both implementation, and I realized that System.Net.WebSockets.ClientWebSocket is using HTTP CONNECT tunelling, whereas WebSocket4Net is sending the handshake request directly to the proxy. This behavior means that :

  • if we're connecting via HTTPS, the proxy has to be HTTPS as well, otherwise the SSL handshake doesn't work
  • if the proxy doesn't understand the websocket URL scheme, it just rejects the request with a 400 error

IMO WebSocket4Net should use HTTP CONNECT tunelling, it would work in much more situations.

Also, I see there's a Proxy property in addition to the httpConnectProxy parameter. What's the difference? What can I set the property to ? I don't see any implementation of IProxyConnector in the library.

TLS Example

I am trying to connect to a websocket server using TLS and I am receiving a exception "The authentication or decryption has failed."

The URI I am passing is :

"wss://ortc-developers2-uswest2-s0001.realtime.co:443/broadcast/926/WNWJYJUQ/websocket"

My constructor looks like

_websocket = new WebSocket(uri, SslProtocols.Tls12.ToString(), WebSocketVersion.Rfc6455);

(I am pretty sure this is wrong, but I do not see any docs)

Subprotocol

I am using WebSocket4Net as a client to a nodejs server. I am getting an exception in my .NET app "subprotocol doesn't match". In node, I am using nodejs-websocket.

Any help would be greatly appreciated.
Thanks

Implemention of PING/PONG unable to detect connection failures

The OnPingTimerCallback refuses to send another PING until it first receives a pending PONG, thus rendering the websocket unable to detect connection failures.

Suggested fix is to either:

  • detect when a pong "timeout" has occurred and call a user supplied "pong timeout error handler."
  • try sending an un-solicited PONG.
        private void OnPingTimerCallback(object state)
        {
            if (!string.IsNullOrEmpty(m_LastPingRequest) && !m_LastPingRequest.Equals(LastPongResponse))
            {
                //have not got last response
                // Verify that the remote endpoint is still responsive 
                // by sending an un-solicited PONG frame:
                try {
                    protocolProcessor.SendPong(this, "");
                } catch (Exception e) {
                    OnError(e);
                    return;
                }
                return;
            }
            // ...
        }

Exception on mono only: System.Net.Sockets.SocketException: An address incompatible with the requested protocol was used

I can connect to a wss just fine running in windows, but am getting the following exception only on mono:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Net.Sockets.SocketException: An address incompatible with the requested protocol was used
  at System.Net.Sockets.Socket..ctor (System.Net.Sockets.AddressFamily addressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) [0x0005d] in <bd46d4d4f7964dfa9beea098499ab597>:0 
  at System.Net.Sockets.Socket.ConnectAsync (System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType, System.Net.Sockets.SocketAsyncEventArgs e) [0x0000b] in <bd46d4d4f7964dfa9beea098499ab597>:0 
  at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in <8f2c484307284b51944a1a13a14c0266>:0 
   --- End of inner exception stack trace ---
  at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00053] in <8f2c484307284b51944a1a13a14c0266>:0 
  at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in <8f2c484307284b51944a1a13a14c0266>:0 
  at SuperSocket.ClientEngine.ConnectAsyncExtension.ConnectAsync (System.Net.EndPoint remoteEndPoint, SuperSocket.ClientEngine.ConnectedCallback callback, System.Object state) [0x00039] in <4ba236fbf29248a4985a92e6e3907e4a>:0 
  at SuperSocket.ClientEngine.TcpClientSession.Connect () [0x00074] in <4ba236fbf29248a4985a92e6e3907e4a>:0 
  at WebSocket4Net.WebSocket.Open () [0x0003a] in <4ba236fbf29248a4985a92e6e3907e4a>:0 

I am calling the constructor with one parameter. Have tried latest stable 0.14.1 and also latest beta 0.15 beta6 and get same issue on both. Am running mono 4.6.2 on ubuntu.

Need to specify connection timeout

When connecting to remote server from phone, sometimes there is problem with connection (switching from mobile data to wifi etc), but I have to wait 1 minute before I get notified. Would be nice, if I could set timeout to custom amount eg 5 secs.

Null reference exception in websocket4net client when the websocket server process is abruptly closed

Hi,
I have a websocket4net client connected to an IIS web socket server. When I stop the websocket app pool in IIS the following exception is thrown on the websocket4net client
Exception Info: System.NullReferenceException at WebSocket4Net.Protocol.DraftHybi10Processor.SendCloseHandshake(WebSocket4Net.WebSocket, Int32, System.String) at WebSocket4Net.WebSocket.OnDataReceived(Byte[], Int32, Int32) at SuperSocket.ClientEngine.SslStreamTcpSession.OnDataRead(System.IAsyncResult) at System.Net.LazyAsyncResult.Complete(IntPtr) at System.Net.LazyAsyncResult.ProtectedInvokeCallback(System.Object, IntPtr) at System.Net.Security._SslStream.ProcessFrameBody(Int32, Byte[], Int32, Int32, System.Net.AsyncProtocolRequest) at System.Net.Security._SslStream.ReadFrameCallback(System.Net.AsyncProtocolRequest) at System.Net.AsyncProtocolRequest.CompleteRequest(Int32) at System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(Int32) at System.Net.FixedSizeReader.ReadCallback(System.IAsyncResult) at System.Net.LazyAsyncResult.Complete(IntPtr) at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) at System.Net.ContextAwareResult.Complete(IntPtr) at System.Net.LazyAsyncResult.ProtectedInvokeCallback(System.Object, IntPtr) at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32, UInt32, System.Threading.NativeOverlapped*) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)

Please let me know if there is any existing fix for this?

Websocket connection closes after a few minutes

Hi,
I'm using WebSocket4Net to send JSON-RPC calls to a media server which is event based. After a few minutes connection is lost and the server log indicates that it can not find connection to the client. Is there any way to keep the connection open? I've also turned on the auto send ping but no luck there too.
Thanks

ObjectDisposedException while closing connection

Hi. There was an exception at one of our servers because of network problems. Service app was crashed.
Details from windows event log:

Description: The process was terminated due to an unhandled exception
Exception Info: System.ObjectDisposedException
Stack:
at System.Threading.TimerQueueTimer.Change(UInt32, UInt32)
at WebSocket4Net.WebSocket.FireClosed()
at SuperSocket.ClientEngine.TcpClientSession.TrySend(System.ArraySegment'1)
at SuperSocket.ClientEngine.ClientSession.Send(System.ArraySegment'1)
at SuperSocket.ClientEngine.ClientSession.Send(Byte[], Int32, Int32)
at WebSocket4Net.Protocol.DraftHybi10Processor.SendCloseHandshake(WebSocket4Net.WebSocket, Int32, System.String)
at WebSocket4Net.Command.Close.ExecuteCommand(WebSocket4Net.WebSocket, WebSocket4Net.WebSocketCommandInfo)
at WebSocket4Net.WebSocket.ExecuteCommand(WebSocket4Net.WebSocketCommandInfo)
at WebSocket4Net.WebSocket.OnDataReceived(Byte[], Int32, Int32)
at SuperSocket.ClientEngine.AsyncTcpSession.ProcessReceive(System.Net.Sockets.SocketAsyncEventArgs)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(System.Net.Sockets.SocketError, Int32, System.Net.Sockets.SocketFlags)
at System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32, UInt32, System.Threading.NativeOverlapped_)
at System.Threading.IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped)

I have watched the sources and found issue in WebSocket4Net.WebSocket.Clear method. It resets m_WebSocketTimer before disposing it.
I think you may just dispose timer, without calling this.m_WebSocketTimer.Change(Timeout.Infinite, Timeout.Infinite);
Or to provide thread-safety for m_WebSocketTimer.

Exception was in WebSocket4Net 0.11, but in 0.14.1 this behaviour is the same, as i see.
Exception is very rare, it happened for the first time during last 2 years.

Thanks.

"unknown server protocol version"

Hi,
I was using WebSocket4Net lib for receiving MtGox bitcoin streaming data:
"ws://websocket.mtgox.com/mtgox"

It was working very good until yesterday. Then I started getting the following Error:
"unknown server protocol version"
I believe MtGox changed something in their API and probably some of the response headers are missing (such as the version field). I've tried to contact them but I didn't get a reply yet.

But - I'm able to connect the above WebSocket via javascript in chrome, and I receive the streaming data normally.

Is it possible for WebSocket4Net to connect the way chrome does? (maybe less restrictive with the response headers).

Thanks in advance,
Shlomi

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib' issue for .NET 4.0 version

Hi,

I'm receiving following build error when compiling on pure .NET 4.0 machine with 4.0 version of WebSocket4Net 14.1.0

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Microsoft.WinFX.targets(269, 9): error MC1000: Unknown build error, 'Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.'

It appears (according to http://stackoverflow.com/questions/13748055/could-not-load-type-system-runtime-compilerservices-extensionattribute-from-as) that ilmerge to join SuperSocket.ClientEngine.dll and WebSocket4Net.dll was run with incorrect parameters. This is also visible when I open manifest for this assembly with ildasm:

image

This should be System.Core in this line instead of mscorlib

Could you please re-release the 14.1 version of WebSocket4Net properly built for .NET 4.0?

WebSocket.Send on iOS does not fail if we remove the network

I was testing our app resilience to network failures, and on WP, all was fine.
But on iOS, no Close/Error event is fired, Send just "sends", without any error.

Is this know?

Shouldn't the events for Closed or Error at least fire as they do on WP?

Websocket hangs on certain proxies

Websocket can hang if used with some proxies.
After calling WebSocket.Open no events (OnWsClosed, OnWsOpened, OnWsError) are raised and some internal thread starts to generate high CPU usage.

More info:
ProxyConnectorBase.AsyncEventArgsCompleted receives an empty buffer - SocketAsyncEventArgs.Buffer is filled with zeros, Offset and BytesTransferred are 0. It calls HttpConnectProxy.ProcessReceive where e.Buffer.SearchMark returns -1 and executes this code:

            if (result < 0)
            {
                int total = e.Offset + e.BytesTransferred;

                if(total >= m_ReceiveBufferSize)
                {
                    OnException("receive buffer size has been exceeded");
                    return;
                }

                e.SetBuffer(total, m_ReceiveBufferSize - total);
                StartReceive(context.Socket, e);
                return;
            }

total becomes 0 too, then StartReceive is called, that raises ProxyConnectorBase.AsyncEventArgsCompleted with empty buffer again and this loop continues infinitely.

I suggest a fix:

                if (e.BytesTransferred == 0)
                {
                    OnException("receive buffer is empty");
                    return;
                }

But I'm not sure could BytesTransferred be zero in other healthy TCP connections.

Proxies to debug the issue with (there are plenty of them in varios online free proxies lists):
111.13.136.46:80
139.162.182.113:80
202.43.147.226:1080

Data loss

I'm using SuperWebSocket.WebSocketServer as a server platform and used to run multiple various tests on this platform/ I noticed that sometimes WebSocket4Net.WebSocket.Send fails with no error and server does not receives any data or errors. Client test code is simple http://pastebin.com/mbUAQ9ht (after connect client sends "request", server send "response" and client sends "request" back - request format does not matter, current test runs "Hello" as request and "OK" as "response"). This issue rises more often on concurrent test when I create and start 4-16 clients with one process. If you'd like I can create separate server-test for you but I believe you'll reproduce this issue self.

I've used current GIT version of WebSocket4Net and run tests on windows 7 machine. This issue very rare and can't be reproduced on 10-1000 requests-responses. Use 1m for fingle connection or 100k for 4-8 connections.

Thanx in advance.

Unable to bind proxy to debug in fiddler

Hit exception that the remoteEndPoint is null in Connect method in SuperSocket.ClientEngine.Proxy when trigger .Open() method.

var proxy = new HttpConnectProxy(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
_socket.Proxy = (SuperSocket.ClientEngine.IProxyConnector)proxy;
_socket.Open();

Modified files on Reference folder

Hey there,

when I build the touch projects, I end up with these modified files below, probably the Reference folder needs an update?

.\Vendor\WebSocket4Net>s
On branch master
Your branch is up-to-date with 'origin/master'.

Changes not staged for commit:
(use "git add ..." to update what will be committed)
(use "git checkout -- ..." to discard changes in working directory)

    modified:   Reference/SuperSocket.ClientEngine/MonoTouch/Debug/SuperSocket.ClientEngine.Common.dll.mdb
    modified:   Reference/SuperSocket.ClientEngine/MonoTouch/Debug/SuperSocket.ClientEngine.Core.dll.mdb
    modified:   Reference/SuperSocket.ClientEngine/MonoTouch/Debug/SuperSocket.ClientEngine.Protocol.dll.mdb
    modified:   Reference/SuperSocket.ClientEngine/MonoTouch/Debug/SuperSocket.ClientEngine.Proxy.dll.mdb

no changes added to commit (use "git add" and/or "git commit -a")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.