Code Monkey home page Code Monkey logo

watsonwebsocket's Introduction

alt tag

Watson Websocket

NuGet Version NuGet

WatsonWebsocket is the EASIEST and FASTEST way to build client and server applications that rely on messaging using websockets. It's. Really. Easy.

Thanks and Appreciation

Many thanks and much appreciation to those that take the time to make this library better!

@BryanCrotaz @FodderMK @caozero @Danatobob @Data33 @AK5nowman @jjxtra @MartyIX @rajeshdua123 @tersers @MacKey-255 @KRookoo1 @joreg @ilsnk @xbarra @mawkish00 @jlopvet @marco-manfroni-perugiatiming @GiaNTizmO @exergist @ebarale99 @WarstekHUN @Rubidium37 @codengine

Test App

A test project for both client (TestClient) and server (TestServer) are included which will help you understand and exercise the class library.

A test project that spawns a server and client and exchanges messages can be found here: https://github.com/jchristn/watsonwebsockettest

Supported Operating Systems

WatsonWebsocket currently relies on websocket support being present in the underlying operating system. Windows 7 does not support websockets.

SSL

SSL is supported in WatsonWebsocket. The constructors for WatsonWsServer and WatsonWsClient accept a bool indicating whether or not SSL should be enabled. Since websockets, and as a byproduct WatsonWebsocket, use HTTPS, they rely on certificates within the certificate store of your operating system. A test certificate is provided in both the TestClient and TestServer projects which can be used for testing purposes. These should NOT be used in production.

For more information on using SSL certificates, please refer to the wiki.

New in v4.0.x

  • Breaking changes
  • Clients now identified by Guid in ClientMetadata
  • ListClients now returns full ClientMetadata
  • Send* methods now take guid as opposed to IpPort
  • Add targeting for .NET 7.0 and .NET Framework 4.8
  • Fix for Blazor WASM, thank you @ebarale99
  • Fix for invalid control characters, thank you @WarstekHUN

Server Example

using WatsonWebsocket;

WatsonWsServer server = new WatsonWsServer("[ip]", port, true|false);
server.ClientConnected += ClientConnected;
server.ClientDisconnected += ClientDisconnected;
server.MessageReceived += MessageReceived; 
server.Start();

static void ClientConnected(object sender, ConnectionEventArgs args) 
{
    Console.WriteLine("Client connected: " + args.Client.ToString());
}

static void ClientDisconnected(object sender, DisconnectionEventArgs args) 
{
    Console.WriteLine("Client disconnected: " + args.Client.ToString());
}

static void MessageReceived(object sender, MessageReceivedEventArgs args) 
{ 
    Console.WriteLine("Message received from " + args.Client.ToString() + ": " + Encoding.UTF8.GetString(args.Data));
}

Client Example

using WatsonWebsocket;

WatsonWsClient client = new WatsonWsClient("[server ip]", [server port], true|false);
client.ServerConnected += ServerConnected;
client.ServerDisconnected += ServerDisconnected;
client.MessageReceived += MessageReceived; 
client.Start(); 

static void MessageReceived(object sender, MessageReceivedEventArgs args) 
{
    Console.WriteLine("Message from server: " + Encoding.UTF8.GetString(args.Data));
}

static void ServerConnected(object sender, EventArgs args) 
{
    Console.WriteLine("Server connected");
}

static void ServerDisconnected(object sender, EventArgs args) 
{
    Console.WriteLine("Server disconnected");
}

Client Example using Browser

server = new WatsonWsServer("http://localhost:9000/");
server.Start();
let socket = new WebSocket("ws://localhost:9000/test/");
socket.onopen = function () { console.log("success"); };
socket.onmessage = function (msg) { console.log(msg.data); };
socket.onclose = function () { console.log("closed"); };
// wait a moment
socket.send("Hello, world!");

Accessing from Outside Localhost

When you configure WatsonWebsocket to listen on 127.0.0.1 or localhost, it will only respond to requests received from within the local machine.

To configure access from other nodes outside of localhost, use the following:

  • Specify the exact DNS hostname upon which WatsonWebsocket should listen in the Server constructor. The HOST header on incoming HTTP requests MUST match this value (this is an operating system limitation)
  • If you want to listen on more than one hostname or IP address, use * or +. You MUST:
    • Run WatsonWebsocket as administrator for this to work (this is an operating system limitation)
    • Use the server constructor that takes distinct hostname and port values (not the URI-based constructor)
  • If you want to use a port number less than 1024, you MUST run WatsonWebsocket as administrator (this is an operating system limitation)
  • If you listen on an interface IP address other than 127.0.0.1, you MAY need to run as administrator (this is operating system dependent)
  • Open a port on your firewall to permit traffic on the TCP port upon which WatsonWebsocket is listening
  • You may have to add URL ACLs, i.e. URL bindings, within the operating system using the netsh command:
    • Check for existing bindings using netsh http show urlacl
    • Add a binding using netsh http add urlacl url=http://[hostname]:[port]/ user=everyone listen=yes
    • Where hostname and port are the values you are using in the constructor
  • If you are using SSL, you will need to install the certificate in the certificate store and retrieve the thumbprint
  • If you're still having problems, please do not hesitate to file an issue here, and I will do my best to help and update the documentation.

Version History

Please refer to CHANGELOG.md for details.

watsonwebsocket's People

Contributors

berik99 avatar bryancrotaz avatar data33 avatar foddermk avatar giantizmo avatar ilsnk avatar jchristn avatar joreg avatar mackey-255 avatar martyix avatar tersers avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

watsonwebsocket's Issues

Rate Throttling Behavior

So if I send several dozen msgs as fast as possible to Chromium, a group of them (say a dozen) go out instantly back to back...
Then only a single message is sent at a time on an interval of approximately one second... for about 2 or 3 messages.
Then another dozen or so are sent rapid-fire together. Then more individual slow ones.

What is going on here?

I looked through the Watson code for "limit" "rate" and "throttl" but didn't find anything.

How to use SSL under Linux (Debian)?

I created a simple WatsonWsServer and set the ssl bool to true but how do i specify the ssl certificate to use under debian (since there is no netsh command available)?

Proxy support ?

Hello, I'm working on a windows forms application where I have a requirement to connect to a WebSocket connection, I have tried WebSocket-sharp and websocket4net both libraries are not very well maintained now
So the problems which I faced using them are

  • They don't seem to offer good support for proxy connections
  • And they are not maintained now.

So my question is can WatsonWebsocket connect through the system proxy without explicitly providing any proxy credentials (The client which we are working has enabled proxy in their system HTTP request were working fine, but now the websocket)

Unable to listen on 'localhost'

I'm using 2.0.2 version from NuGet.
The docs say

When you configure WatsonWebsocket to listen on 127.0.0.1 or localhost

But I can't listen on "localhost" as that produces an exception on IPAddress.Parse call. I can't listen on "127.0.0.1" either as I get "Access denied" exception and I don't want to run any netsh commands to workaround that.

Is ClientConnected Premature

Hello,

I'm using this library to host a playground while I learn javascript. I've noticed that the ClientConnected event is called before the client is initialized and added to the collection. Is there a reason why the ClientConnected event would be called so early when there are a few instances where the client wouldn't actually be accepted?

I'm also using your SimpleTCP library in another project and the ClientConnected event is the last thing to be called when accepting a connection. I only program as a hobby so I wouldn't know what to look for to determine if this is because of fundamental differences between Web and TCP socket.

Thank you!

Mono client on Debian isn't protocol compliant

Windows server, Debian client on Raspberry Pi

Error on server side: Invalid data format for the specific protocol operation

This is happening in the ClientWebSocket. I suspect an endianness or Mono issue. Same client code works fine on Windows.

Send vs SendAsync

hei joel,

is there a reason why this library has only SendAsync functions while the very similar SimpleTcp has only Send (non-async) versions? Shouldn't both make sense in both cases?

WebSocket Server not opening the listening port

Just checked on 3 different machines:

Watson Websocket server to be listening on port 1234

Windows Server 2012R2: OK
Windows 7 (Run as User): Port not open
Windows 7 (Run as Administrator): Port opened by the system process (PID 4). Data not being handled by WatsonWebsocket
Windows 10: Port not open

Do you have any suggestion?

Connection on real network not working

I tried to connect from another PC on the LAN and can not get it working. Using the provided testserver and client.

Client just printing "Server disconnected" on connection attempt.
Firewalls on both machines down.

Connections from same PC (127.0.0.1) work as expected.

Halt execution until server/client is ready after calling start

Is there a way to block execution until the server is actually ready? Atm I'm doing a while loop that checks the IsListening variable which seems wasteful. Same with the client, except checking if the client IsConnected.

I would love to be able to do something like:

await WebsocketServer.Start()
await WebsocketClient.Start()

Websocket URLs

Will this project work with Websockets with long urls like
wss://192.168.0.123:8002/api/v2/channels/samsung.remote.control?name=xyzzy

If yes, how to set up the client?

Listening on more than one hostname or IP address

Hello,

I tried the following on windows 10 and ran as administrator:

server = new WatsonWsServer("127.0.0.1+host1", 8081, false);

But this does not work. Could you share an example of listening on more than one host/ip ?

Thank you very much,
Jules

SSL Issue

Hi,

  1. We recently installed an SSL certificate on our server.

  2. Our base socket was running without SSL before. "ws://". Port is 9000.

  3. Everything was fine.

  4. After SSL installation, we made SSL as true in the socket program and re-ran it.

  5. The connection to the socket stopped. I understand that this is because of certificate installation.

  6. I followed your instructions available here - https://github.com/jchristn/WatsonWebserver/wiki/Using-SSL-on-Windows

  7. When I ran netsh command to add certificate, I got a message that certificate is already added to 0.0.0.0:443. I understand that while installing the server, it got added automatically.

  8. I tried to add this certificate to port 9000 but got an error - "SSL Certificate add failed, Error: 1312 A specified logon session does not exist. It may already have been terminated."

  9. I am sure I am missing something here.

Please guide.

Thanks,
Rajesh

ClientConnectedEventArgs.HttpRequest.get returned null

Version 2.1.1 from NuGet
for ClientConnected event I get this

System.NullReferenceException: 'Object reference not set to an instance of an object.'
WatsonWebsocket.ClientConnectedEventArgs.HttpRequest.get returned null.

An operation was attempted on a nonexistent network connection

When I navigate Chromium to a different page--thereby terminating existing socket connection that I've made to server-- the server throws this exception:
An operation was attempted on a nonexistent network connection

This exception occurs before the ClientDisconnected() event fires. The ClientDisconnected event fires and behaves as normal. The server also continues to run as normal.

SendAsync - Taking High CPU

Hi Joel,

I have installed the latest version available on Nuget. The socket server was running pretty fine till yesterday. From today morning, we are experiencing a high CPU usage while sending the data packets to the connected clients.

Can you please help?

Thanks

MessageReceived event missing while simultaneously sending in WatsonWsClient

Hi,

I have a problem and I don't know where to place it not being a developer at all.
I am using this websocket to receive and send commands to SoundCraft UI mixer.
Works fine up to one problem, that the reply to one (short) sent command won't raise the event and I don't know if it has something do with threading or anything else blocking the moment when the message is coming in.
I tested it with making a second client and handle the events there to see if it is really coming in, and it is.
The Class handling the Connection is a static class so that the application is using only one single connection throughout its lifetime.
Any hint what I am doing wrong?

   public static WatsonWsClient MixConnection { get; set; }
        public static void InitMixer(string URL)
        {
            Uri Uri = new Uri(URL);
            MixConnection = new WatsonWsClient(Uri);
            MixConnection.ServerConnected += EventOnOpen;
            MixConnection.ServerDisconnected += EventOnClose;
            MixConnection.MessageReceived += EventOnMessage;

            //WatsonWsClient TestCon = new WatsonWsClient(Uri);
            //TestCon.MessageReceived += EventOnMessage;
            //TestCon.Start();
        }

        private static void EventOnMessage(object sender, MessageReceivedEventArgs e)
        {
           ......
        }

Unable to make minimal example work. Am I to upgrade the http connection manually first?

Hi! I'm trying to use WatsonWebsocket with Unity, but I have some issues getting started.

Server:

using UnityEngine;
using WatsonWebsocket;

public class WebSocketServer : MonoBehaviour
{
    
    private string address = "127.0.0.1";
    private ushort port = 13337;

    private WatsonWsServer _ws;

    private void Awake()
    {
        string header = "[Server] ";
        _ws = new WatsonWsServer(address, port, false)
        {
            Logger = Debug.LogError
        };
        _ws.Start();
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log(_ws.IsListening);
    }
}

Client (fetched from websockets documentation):

import asyncio
import websockets


async def hello():
    uri = "ws://127.0.0.1:13337"
    async with websockets.connect(uri) as websocket:
        await websocket.send("test")
        recv = await websocket.recv()

asyncio.get_event_loop().run_until_complete(hello())

Error log:

[WatsonWsServer] starting http://127.0.0.1:13337/
UnityEngine.Debug:LogError(Object)
WatsonWebsocket.WatsonWsServer:Start()
WebSocketServer:Awake() (at Assets/Scripts/WebSocketServer.cs:21)

True
UnityEngine.Debug:Log(Object)
WebSocketServer:Update() (at Assets/Scripts/WebSocketServer.cs:27)

[WatsonWsServer] non-websocket request rejected from 127.0.0.1:22270
UnityEngine.Debug:LogError(Object)
WatsonWebsocket.<AcceptConnections>d__47:MoveNext()
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback()

Assets\Scripts\WebSocketServer.cs(14,16): warning CS0219: The variable 'header' is assigned but its value is never used

From what I see in the source it seems like IsWebSocketRequest fails first, and then the connection is rejected since I haven't defined a HttpHandler?

if (!ctx.Request.IsWebSocketRequest)
{
if (HttpHandler == null)
{
Logger?.Invoke(_Header + "non-websocket request rejected from " + ipPort);
ctx.Response.StatusCode = 400;
ctx.Response.Close();
}
else
{
Logger?.Invoke(_Header + "non-websocket request from " + ipPort + " HTTP-forwarded: " + ctx.Request.HttpMethod.ToString() + " " + ctx.Request.RawUrl);
HttpHandler.Invoke(ctx);
}

Stack Overflow

I just noticed the following exception when checking our development server. There were like 5 clients connected and it seemed to happen after one disconnected. Any ideas what might have caused this issue?

Stack overflow.
at Interop+WebSocket.WebSocketCompleteAction(System.Runtime.InteropServices.SafeHandle, IntPtr, UInt32)
at System.Net.WebSockets.WebSocketProtocolComponent.WebSocketCompleteAction(System.Net.WebSockets.WebSocketBase, IntPtr, Int32)
at System.Net.WebSockets.WebSocketBase+WebSocketOperation+d__19.MoveNext()
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[[System.__Canon, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Net.WebSockets.WebSocketBase+WebSocketOperation+d__19, System.Net.HttpListener, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]].MoveNext(System.Threading.Thread)
at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Runtime.CompilerServices.IAsyncStateMachineBox, Boolean)
at System.Threading.Tasks.Task.RunContinuations(System.Object)
at System.Threading.Tasks.Task.CancellationCleanupLogic()
at System.Threading.Tasks.Task.TrySetCanceled(System.Threading.CancellationToken, System.Object)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1[[System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].SetException(System.Exception, System.Threading.Tasks.Task1 ByRef)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1[[System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].SetException(System.Exception) at System.Net.WebSockets.WebSocketHttpListenerDuplexStream+<ReadAsyncCore>d__30.MoveNext() at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[[System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Net.WebSockets.WebSocketHttpListenerDuplexStream+<ReadAsyncCore>d__30, System.Net.HttpListener, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]].MoveNext(System.Threading.Thread) at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Runtime.CompilerServices.IAsyncStateMachineBox, Boolean) at System.Threading.Tasks.Task.RunContinuations(System.Object) at System.Threading.Tasks.Task.CancellationCleanupLogic() at System.Threading.Tasks.Task.TrySetCanceled(System.Threading.CancellationToken, System.Object) at System.Threading.Tasks.TaskCompletionSource1[[System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].TrySetCanceled(System.Threading.CancellationToken)
at System.Threading.Tasks.TaskCompletionSource`1[[System.Int32, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].TrySetCanceled()
at System.Net.WebSockets.WebSocketHttpListenerDuplexStream.OnCancel(System.Object)
at System.Threading.CancellationTokenSource+CallbackNode+<>c.b__9_0(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.CancellationTokenSource+CallbackNode.ExecuteCallback()
at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean)
at System.Threading.CancellationTokenSource.NotifyCancellation(Boolean)
at System.Threading.CancellationTokenSource.Cancel()
at System.Net.WebSockets.WebSocketBase+OutstandingOperationHelper.CancelIO()
at System.Net.WebSockets.WebSocketBase.Abort()
at System.Net.WebSockets.WebSocketBase.OnBackgroundTaskException(System.Exception)
at System.Net.WebSockets.WebSocketBase+d__77.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[[System.Net.WebSockets.WebSocketBase+d__77, System.Net.HttpListener, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]](d__77 ByRef)
at System.Net.WebSockets.WebSocketBase.OnKeepAlive(System.Object)
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(System.Threading.Thread, System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.TimerQueueTimer.CallCallback(Boolean)
at System.Threading.TimerQueueTimer.Fire(Boolean)
at System.Threading.ThreadPoolWorkQueue.Dispatch()

Send message to all connected clients issue

Hello!

I'm not sure how to do this properly so I could be doing this wrong but basically I'm trying to send a messages to all connected clients. This is the code I'm using:

internal static void WSSendUpdate(string data)
        {
            var clients = new List<string>(_WSServer.ListClients());
            if (clients.Count() > 0)
            {
                foreach (var client in clients)
                {
                    _WSServer.SendAsync(data);
                }
            }
        }

This works well except for when a client disconnects. Client connects, data streams great no problem, then on disconnect this is what happens:

[WatsonWsServer **IP**:49753] disconnected
[WatsonWsServer **IP**:49753] disposed
[WatsonWsServer **IP**:49753] disposed
[WatsonWsServer **IP**:49753] disposed
[WatsonWsServer **IP**:49753] disposed
[WatsonWsServer **IP**:49753] disposed
[WatsonWsServer **IP**:49753] disposed
[WatsonWsServer **IP**:49753] disposed
[WatsonWsServer **IP**:49753] disposed
[WatsonWsServer **IP**:49753] disposed

And this repeats infinitely every time the WSSendUpdate() method is called and bascially locks up the application.

Any help or suggestions on this would be greatly appreciated!

Thanks

TestSslClient and TestSslServer don't exist

The readme makes mention of a TestSslClient and TestSslServer but these don't seem to exist in the project. There is also reference to test-certificate.txt but it looks like that was removed on Jun 12 with commit 44e8ace. Is the readme incorrect or were the files removed by accident?

Disposing WatsonWSServer doesn't free port

hey joel,

we just discovered that disposing the server doesn't free the port. simple to reproduce using these three lines:

var ws = new WatsonWsServer("127.0.0.1", 6666, false);
ws.Start();
ws.Dispose();

are we missing anything in shutting it down?

Is adding asynchronous non-blocking support possible?

I noticed that the MessageReceived event is synchronous and blocking. I can't react to new messages while still processing a long-running previous one.

Would it be significant lift to add an asynchronous Task MessageReceived event that would allow immediate reaction to messages as fast as the server can process them?

ClientDisonnectedEventArgs misspell

///


/// Event arguments for when a client disconnects from the server.
///

public class ClientDisonnectedEventArgs : EventArgs
{
internal ClientDisonnectedEventArgs(string ipPort)
{
this.IpPort = ipPort;
}

/// <summary>The IP:port of the client.</summary>
public string IpPort { get; }

}

ClientDisconnectedEventArgs

listening on 0.0.0.0 as non-admin

hei joel,

under "Accessing from Outside Localhost" you write: "If you want to listen on more than one hostname or IP address, use * or +. You MUST run WatsonWebsocket as administrator for this to work (this is an operating system limitation)"

my questions:

  • is there a difference between * and + and how do they relate to 0.0.0.0?
  • i've previously used the fleck websocket server where it is possible to listen on 0.0.0.0 without running as admin. so i wonder if there shouldn't also be a way with watson to do so?!

killClient has gone in v2?

I'm upgrading to the NuGet library to get .Net Standard.
What's the replacement/workaround for Server.KillClient that was there in v1?

Communication with JS websockets

Thanks for your work with this library. Really appreciate it.

I'm trying to communicate with a JS WebSocket. Roughly like:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <!-- <script src="app.js" type="text/javascript"></script> -->
    <script type="text/javascript">
        var socket = new WebSocket('http://localhost:8083/socket');
        socket.onopen = function() {
           // alert('handshake successfully established. May send data now...');
		   socket.send("Hi there from browser.");
        };
		socket.onmessage = function (evt) {
                //alert("About to receive data");
                var received_msg = evt.data;
                alert("Message received = "+received_msg);
            };
        socket.onclose = function() {
            alert('connection closed');
        };
    </script>
</body>
</html>

But http:// is not supported: SyntaxError: An invalid or illegal string was specified

This SO question seems to be related, but I still couldn't make it work.

Do you have any hints?

Getting error while try start server from outside localhost

I try to start WatsonWsServer with ip and port are allow firewall and already add ACL URL.
Here is my code:
WatsonWsServer server = new WatsonWsServer(_ip, _port,true);

            server.MessageReceived += OnMessage;
            server.ClientConnected += Server_ClientConnected;
            server.ClientDisconnected += Server_ClientDisconnected;
            log.Info("Begin start socket server");
            server.Start();

and i get this error.
Failed to listen on prefix 'https://{ip}:1234/' because it conflicts with an existing registration on the machine.
I already check netstat and port is not using at anywhere else. How can i fix it

Is this going to work with .NET 5?

I notice this library depends on HttpListener (which I believe was deprecated some time ago). Will that create a problem for .NET 5?

I've read controversy over the deprecation of HttpListener. There have been some other projects started to write new lightweight Http servers that run on mono and core.

[DisconnectClient] Bad behavior with local address

When you try to kick clients with DisconnectClient, you must add the ip:port-String from the client (for example 127.0.0.1:1234).
But the server seems to transform 127.0.0.1 to ::1:

image
image

StackTrace

One or more errors occurred. (The received message type 'Text' is invalid after calling WebSocket.CloseAsync. WebSocket.CloseAsync should only be used if no more data is expected from the remote endpoint. Use 'WebSocket.CloseOutputAsync' instead to keep being able to receive data but close the output channel.)

at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at WatsonWebsocket.WatsonWsServer.DisconnectClient(String ipPort)
at Launcher.Program.ClientConnected(Object sender, ClientConnectedEventArgs args)
at WatsonWebsocket.WatsonWsServer.<>c__DisplayClass47_1.<<AcceptConnections>b__1>d.MoveNext()"

WatsonWebsocket project

Hi @jchristn ,

Interesting to find this project ! I am always looking to another solution without Edit/Add/Polish it and broken history ๐Ÿ‘
I think people would like to know if you project handle what websocket-sharp can do and specially about performance, memory footprint, multithreaded and how much connection it can handle.
This would motivate people to move to your project (myself include).

Also a CI with tests would be awesome !

I know that it is easier to ask than doing it. I would help you but am already handling different projects myself ๐Ÿ˜ข

Communication with JS websockets

Thanks for your work with this library. I had some problems with this library.Please forgive my poor English.

<title>Title</title> <script> var socket = new WebSocket("ws://127.0.0.1:4000/"); try { socket.onopen = function () { console.log("sucess"); }; socket.onmessage = function (msg) { console.log(msg.data); }; socket.onclose = function () { console.log("Closed"); }; } catch (ex) { log(ex); } </script>

server c#
static void Main(string[] args)
{
using (WatsonWsServer wss = new WatsonWsServer("127.0.0.1", 4000, false))
{
wss.ClientConnected += (s, e) =>
{
Console.WriteLine(e.IpPort + " is connected.");
};

            wss.ClientDisconnected += (s, e) =>
            {
                Console.WriteLine(e.IpPort + " is disconnected.");
            };

            wss.MessageReceived += async (s, e) =>
            {
                Console.WriteLine(BitConverter.ToString(e.Data));
                await wss.SendAsync(e.IpPort, e.Data);
            };
            wss.Start();

            Console.WriteLine("press any key to exit.....");
            Console.ReadKey();
        }

Error
WebSocket connection to 'ws://127.0.0.1:4000/socket' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

Do you have any hints?

Multiple connections between client and server

Hello.

I'm not sure whether this is a feature request or a question.

I'm looking to implement multiple, concurrent websocket connections between a client and a server. So that there can be 1-n websockets concurrently between the same server and client.

Is this possible with WatsonWebsocket? My initial impression is no - since the connections seem to be identified by ipPort, which is unique to one client, but doesn't leave any way to address multiple connections from the same client (where ip and port would both be identical)

If I'm missing something and this is possible - that's wonderful. Otherwise consider it a feature request :)

How to re-connect to server?

I hope my client just listens to the server, even if the server hasnโ€™t started yet .

var WebSocket_Client = new WatsonWsClient("127.0.0.1",9000,false);
await WebSocket_Client .StartAsync();

Could u help me?
Thanks.

Getting Error While Disconnecting a Client

Hi,

We are getting errors very frequently while disconnecting the client. Here is the complete stack trace. Please help -

Application: XXXXXXXXXX
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.HttpListenerException
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at System.Net.WebSockets.WebSocketHttpListenerDuplexStream+d__30.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(System.Threading.Tasks.Task)
at System.Net.WebSockets.WebSocketBase+WebSocketOperation+d__19.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(System.Threading.Tasks.Task)
at System.Net.WebSockets.WebSocketBase+d__56.MoveNext()

Exception Info: System.Net.WebSockets.WebSocketException
at System.Net.WebSockets.WebSocketBase.ThrowIfConvertibleException(System.String, System.Exception, System.Threading.CancellationToken, Boolean)
at System.Net.WebSockets.WebSocketBase+d__56.MoveNext()

Exception Info: System.AggregateException
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean)
at System.Threading.Tasks.Task.Wait(Int32, System.Threading.CancellationToken)
at WatsonWebsocket.WatsonWsServer.DisconnectClient(System.String)
at _19_neostox_msgbroadcaster.Program+d__7.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_1(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(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.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

Thanks and regards,
Rajesh

Sending binary data directly as text is no longer possible

Prior to 2.2.0, this is how text messages were sent with binary data:

server.SendAsync(EndPoint, bytes, System.Net.WebSockets.WebSocketMessageType.Text);

In 2.2.0, this signature is gone, requiring one to use this signature:

server.SendAsync(EndPoint, System.Text.Encoding.UTF8.GetString(bytes));

There is an overload that takes a string, but this requires an extra step to decode the bytes into a string. Seems like this step could be skipped if the internal web socket code could just send the bytes but mark it as text instead of binary.

Combine both websocket server and client

Hello:
I have one special request, I need some help.
I need some kind of web socket relay program. I have one very fast web socket data source, the server is not in my control. But the external web socket server generates huge amount of text data, I can write one web socket client to receive the huge amount of data, but less than 10% of the data is needed. As the external web socket server generates too much data, my web socket client is always freeze, yet less than 10% of the data is useful.
I want to write a web socket relay program, which is one web socket client for the external web socket server, but at the same time, acts as one internal web socket server, send only those 10% useful data to another web socket client.
Another web socket client can process all the useful data. In this design, the web socket relay program will be busy to process all the web socket data, but another web socket client will not be freeze to process only 10% of total data received.
Let me know if my thinking is practical, if yes, can you provide some code example.
Thanks,

Nonexistent network connection error

I am building a .net plugin with this great Websocket server tool.
The plugin opens up a websocket server and allows browser to connect and send messages through localhost:9000.
There is a very interesting case. If the user opens a coonection and close browser, which will disconnect, within about 25 seconds, it returns this error which can not be handled:
HttpListenerException: An operation was attempted on a nonexistent network connection
It eventually causes a crash.
Does anyone have the same experience?

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.