{"id":14963579,"url":"https://github.com/dotnet/watsontcp","last_synced_at":"2025-05-14T03:06:43.746Z","repository":{"id":12849550,"uuid":"72965948","full_name":"dotnet/WatsonTcp","owner":"dotnet","description":"WatsonTcp is the easiest way to build TCP-based clients and servers in C#.","archived":false,"fork":false,"pushed_at":"2025-03-04T16:50:44.000Z","size":3074,"stargazers_count":629,"open_issues_count":10,"forks_count":121,"subscribers_count":26,"default_branch":"master","last_synced_at":"2025-05-13T10:48:51.718Z","etag":null,"topics":["api","async-tcp-server","client","framing","messaging","mono","mono-environments","nuget","rpc","server","ssl","ssl-support","tcp","tls"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dotnet.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["jchristn"],"custom":["https://paypal.me/joelchristner"]}},"created_at":"2016-11-06T02:40:24.000Z","updated_at":"2025-05-13T01:10:09.000Z","dependencies_parsed_at":"2024-09-13T19:59:31.502Z","dependency_job_id":"bb8ca6fe-c9ad-4d0f-8fcd-d1a85be88f18","html_url":"https://github.com/dotnet/WatsonTcp","commit_stats":{"total_commits":324,"total_committers":20,"mean_commits":16.2,"dds":0.5246913580246914,"last_synced_commit":"49d796e4d794ae1f7e74c5778ae8afb73bb4947b"},"previous_names":["jchristn/watsontcp"],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dotnet%2FWatsonTcp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dotnet%2FWatsonTcp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dotnet%2FWatsonTcp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dotnet%2FWatsonTcp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dotnet","download_url":"https://codeload.github.com/dotnet/WatsonTcp/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254059500,"owners_count":22007768,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","async-tcp-server","client","framing","messaging","mono","mono-environments","nuget","rpc","server","ssl","ssl-support","tcp","tls"],"created_at":"2024-09-24T13:31:49.211Z","updated_at":"2025-05-14T03:06:43.725Z","avatar_url":"https://github.com/dotnet.png","language":"C#","funding_links":["https://github.com/sponsors/jchristn","https://paypal.me/joelchristner"],"categories":[],"sub_categories":[],"readme":"![alt tag](https://github.com/jchristn/watsontcp/blob/master/assets/watson.ico)\n\n# WatsonTcp\n\n[![NuGet Version](https://img.shields.io/nuget/v/WatsonTcp.svg?style=flat)](https://www.nuget.org/packages/WatsonTcp/) [![NuGet](https://img.shields.io/nuget/dt/WatsonTcp.svg)](https://www.nuget.org/packages/WatsonTcp) \n\nWatsonTcp is the fastest, easiest, most efficient way to build TCP-based clients and servers in C# with integrated framing, reliable transmission, and fast disconnect detection.\n\n**IMPORTANT** WatsonTcp provides framing to ensure message-level delivery which also dictates that you must either 1) use WatsonTcp for both the server and the client, or, 2) ensure that your client/server exchange messages with the WatsonTcp node using WatsonTcp's framing.  Refer to ```FRAMING.md``` for a reference on WatsonTcp message structure.\n\n- If you want a library that doesn't use framing, but has a similar implementation, use [SuperSimpleTcp](https://github.com/jchristn/supersimpletcp)\n- If you want a library that doesn't use framing and provides explicit control over how much data to read, use [CavemanTcp](https://github.com/jchristn/cavemantcp)\n\n## .NET Foundation\n\nThis project is part of the [.NET Foundation](http://www.dotnetfoundation.org/projects) along with other projects like [the .NET Runtime](https://github.com/dotnet/runtime/).\n\n## Contributions\n\nSpecial thanks to the following people for their support and contributions to this project!\n\n@brudo @MrMikeJJ @mikkleini @pha3z @crushedice @marek-petak @ozrecsec @developervariety \n@NormenSchwettmann @karstennilsen @motridox @AdamFrisby @Job79 @Dijkstra-ru @playingoDEERUX\n@DuAell @syntacs @zsolt777 @broms95 @Antwns @MartyIX @Jyck @Memphizzz @nirajgenius \n@cee-sharp @jeverz @cbarraco @DenisBalan @Markonius @Ahmed310 @markashleybell \n@thechosensausage @JVemon @eatyouroats @bendablegears @Laiteux @fisherman6v6 @wesoos \n@YorVeX @tovich37 @sancheolz @lunedis @ShayanFiroozi\n\nIf you'd like to contribute, please jump right into the source code and create a pull request, or, file an issue with your enhancement request. \n\n## New in v6.0.x\n\n- Remove unsupported frameworks\n- Async version of ```SyncMessageReceived``` callback\n- Moving usings inside namespace\n- Remove obsolete methods\n- Mark non-async APIs obsolete \n- Modified test projects to use async\n- Ensured background tasks honored cancellation tokens\n- Ability to specify a client's GUID before attempting to connect\n- Remove obsolete methods\n\n## Test Applications\n\nTest projects for both client and server are included which will help you understand and exercise the class library.\n\n## SSL\n\nWatsonTcp supports data exchange with or without SSL.  The server and client classes include constructors that allow you to include fields for the PFX certificate file and password.  An example certificate can be found in the test projects, which has a password of 'password'.\n\n## To Stream or Not To Stream...\n\nWatsonTcp allows you to receive messages using either byte arrays or streams.  Set ```Events.MessageReceived``` if you wish to consume a byte array, or, set ```Events.StreamReceived``` if you wish to consume a stream. \n\nIt is important to note the following:\n\n- When using ```Events.MessageReceived```\n  - The message payload is read from the stream and sent to your application\n  - The event is fired asynchronously and Watson can continue reading messages while your application processes\n- When using ```Events.StreamReceived```\n  - If the message payload is smaller than ```Settings.MaxProxiedStreamSize```, the data is read into a ```MemoryStream``` and sent to your application asynchronously\n  - If the message payload is larger than ```Settings.MaxProxiedStreamSize```, the underlying data stream is sent to your application synchronously, and WatsonTcp will wait until your application responds before continuing to read\n- Only one of ```Events.MessageReceived``` and ```Events.StreamReceived``` should be set; ```Events.MessageReceived``` will be used if both are set\n\n## Including Metadata with a Message\n\nShould you with to include metadata with any message, use the ```Send``` or ```SendAsync``` method that allows you to pass in metadata (```Dictionary\u003cstring, object\u003e```).  Refer to the ```TestClient```, ```TestServer```, ```TestClientStream```, and ```TestServerStream``` projects for a full example.  Keys must be of type ```string```.\n \nNote: if you use a class instance as either the value, you'll need to deserialize on the receiving end from JSON.  \n```\nobject myVal = args.Metadata[\"myKey\"];\nMyClass instance = myVal.ToObject\u003cMyClass\u003e();\n```\n\nThis is not necessary if you are using simple types (int, string, etc).  Simply cast to the simple type.\n\n**IMPORTANT**\n\nIdentifying the demarcation between message header and payload is CPU intensive and requires evaluation of the tail end of an internally-managed buffer.  This process of evaluation is performed for *each byte read* until the end of the header is reached.  Thus, is it recommended that the metadata property be used sparingly and with very small amounts of data (less than 1KB).  When used with large amounts of data, CPU utilization will increase dramatically and response time will be very slow.   \n\n### Local vs External Connections\n\n**IMPORTANT**\n* If you specify ```127.0.0.1``` as the listener IP address in WatsonTcpServer, it will only be able to accept connections from within the local host.  \n* To accept connections from other machines:\n  * Use a specific interface IP address, or\n  * Use ```null```, ```*```, ```+```, or ```0.0.0.0``` for the listener IP address (requires admin privileges to listen on any IP address)\n* Make sure you create a permit rule on your firewall to allow inbound connections on that port\n* If you use a port number under 1024, admin privileges will be required\n\n## Running under Mono\n\n.NET Core should always be the preferred option for multi-platform deployments.  However, WatsonTcp works well in Mono environments with the .NET Framework to the extent that we have tested it. It is recommended that when running under Mono, you execute the containing EXE using --server and after using the Mono Ahead-of-Time Compiler (AOT).  Note that TLS 1.2 is hard-coded, which may need to be downgraded to TLS in Mono environments.\n\nNOTE: Windows accepts '0.0.0.0' as an IP address representing any interface.  On Mac and Linux you must be specified ('127.0.0.1' is also acceptable, but '0.0.0.0' is NOT).\n```\nmono --aot=nrgctx-trampolines=8096,nimt-trampolines=8096,ntrampolines=4048 --server myapp.exe\nmono --server myapp.exe\n```\n\n## Examples\n\nThe following examples show a simple client and server example using WatsonTcp without SSL and consuming messages using byte arrays instead of streams.  For full examples, please refer to the ```Test.*``` projects.  \n\n### Server\n```csharp\nusing WatsonTcp;\n\nstatic void Main(string[] args)\n{\n    WatsonTcpServer server = new WatsonTcpServer(\"127.0.0.1\", 9000);\n    server.Events.ClientConnected += ClientConnected;\n    server.Events.ClientDisconnected += ClientDisconnected;\n    server.Events.MessageReceived += MessageReceived; \n    server.Callbacks.SyncRequestReceivedAsync = SyncRequestReceived;\n    server.Start();\n\n    // list clients\n    IEnumerable\u003cClientMetadata\u003e clients = server.ListClients();\n\n    // send a message\n    await server.SendAsync([guid], \"Hello, client!\");\n\n    // send a message with metadata\n    Dictionary\u003cstring, object\u003e md = new Dictionary\u003cstring, object\u003e();\n    md.Add(\"foo\", \"bar\");\n    await server.SendAsync([guid], \"Hello, client!  Here's some metadata!\", md);\n\n    // send and wait for a response\n    try\n    {\n        SyncResponse resp = await server.SendAndWaitAsync(\n            [guid], \n            5000, \n            \"Hey, say hello back within 5 seconds!\");\n\n        Console.WriteLine(\"My friend says: \" + Encoding.UTF8.GetString(resp.Data));\n    }\n    catch (TimeoutException)\n    {\n        Console.WriteLine(\"Too slow...\");\n    } \n}\n\nstatic void ClientConnected(object sender, ConnectionEventArgs args)\n{\n    Console.WriteLine(\"Client connected: \" + args.Client.ToString());\n}\n\nstatic void ClientDisconnected(object sender, DisconnectionEventArgs args)\n{\n    Console.WriteLine(\n        \"Client disconnected: \" \n        + args.Client.ToString() \n        + \": \" \n        + args.Reason.ToString());\n}\n\nstatic void MessageReceived(object sender, MessageReceivedEventArgs args)\n{\n    Console.WriteLine(\n        \"Message from \" \n        + args.Client.ToString() \n        + \": \" \n        + Encoding.UTF8.GetString(args.Data));\n}\n\nstatic async Task\u003cSyncResponse\u003e SyncRequestReceived(SyncRequest req)\n{\n    return new SyncResponse(req, \"Hello back at you!\");\n}\n```\n \n### Client \n```csharp\nusing WatsonTcp;\n\nstatic void Main(string[] args)\n{\n    WatsonTcpClient client = new WatsonTcpClient(\"127.0.0.1\", 9000);\n    client.Events.ServerConnected += ServerConnected;\n    client.Events.ServerDisconnected += ServerDisconnected;\n    client.Events.MessageReceived += MessageReceived; \n    client.Callbacks.SyncRequestReceivedAsync = SyncRequestReceived;\n    client.Connect();\n\n    // check connectivity\n    Console.WriteLine(\"Am I connected?  \" + client.Connected);\n\n    // send a message\n    client.Send(\"Hello!\");\n\n    // send a message with metadata\n    Dictionary\u003cstring, object\u003e md = new Dictionary\u003cstring, object\u003e();\n    md.Add(\"foo\", \"bar\");\n    await client.SendAsync(\"Hello, client!  Here's some metadata!\", md);\n\n    // send and wait for a response\n    try\n    {\n        SyncResponse resp = await client.SendAndWaitAsync(\n            5000, \n            \"Hey, say hello back within 5 seconds!\");\n\n        Console.WriteLine(\"My friend says: \" + Encoding.UTF8.GetString(resp.Data));\n    }\n    catch (TimeoutException)\n    {\n        Console.WriteLine(\"Too slow...\");\n    }  \n}\n\nstatic void MessageReceived(object sender, MessageReceivedEventArgs args)\n{\n    Console.WriteLine(\"Message from server: \" + Encoding.UTF8.GetString(args.Data));\n}\n\nstatic void ServerConnected(object sender, ConnectionEventArgs args)\n{\n    Console.WriteLine(\"Server connected\");\n}\n\nstatic void ServerDisconnected(object sender, DisconnectionEventArgs args)\n{\n    Console.WriteLine(\"Server disconnected\");\n}\n\nstatic async Task\u003cSyncResponse\u003e SyncRequestReceived(SyncRequest req)\n{\n    return new SyncResponse(req, \"Hello back at you!\");\n}\n```\n\n## Example with SSL\n\nThe examples above can be modified to use SSL as follows.  No other changes are needed.  Ensure that the certificate is exported as a PFX file and is resident in the directory of execution.\n```csharp\n// server\nWatsonTcpServer server = new WatsonTcpServer(\"127.0.0.1\", 9000, \"test.pfx\", \"password\"); \nserver.Settings.AcceptInvalidCertificates = true;\nserver.Settings.MutuallyAuthenticate = true;\nserver.Start();\n\n// client\nWatsonTcpClient client = new WatsonTcpClient(\"127.0.0.1\", 9000, \"test.pfx\", \"password\"); \nclient.Settings.AcceptInvalidCertificates = true;\nclient.Settings.MutuallyAuthenticate = true;\nclient.Connect();\n```\n\n## Example with Streams\n\nRefer to the ```Test.ClientStream``` and ```Test.ServerStream``` projects for a full example.  \n```csharp\n// server\nWatsonTcpServer server = new WatsonTcpServer(\"127.0.0.1\", 9000);\nserver.Events.ClientConnected += ClientConnected;\nserver.Events.ClientDisconnected += ClientDisconnected;\nserver.Events.StreamReceived += StreamReceived; \nserver.Start();\n\nstatic void StreamReceived(object sender, StreamReceivedEventArgs args)\n{\n    long bytesRemaining = args.ContentLength;\n    int bytesRead = 0;\n    byte[] buffer = new byte[65536];\n\n    using (MemoryStream ms = new MemoryStream())\n    {\n        while (bytesRemaining \u003e 0)\n        {\n            bytesRead = args.DataStream.Read(buffer, 0, buffer.Length);\n            if (bytesRead \u003e 0)\n            {\n                ms.Write(buffer, 0, bytesRead);\n                bytesRemaining -= bytesRead;\n            }\n        }\n    }\n\n    Console.WriteLine(\n        \"Stream received from \" \n        + args.Client.ToString() \n        + \": \" \n        + Encoding.UTF8.GetString(ms.ToArray())); \n}\n\n// client\nWatsonTcpClient client = new WatsonTcpClient(\"127.0.0.1\", 9000);\nclient.Events.ServerConnected += ServerConnected;\nclient.Events.ServerDisconnected += ServerDisconnected;\nclient.Events.StreamReceived += StreamReceived; \nclient.Connect();\n\nstatic void StreamReceived(object sender, StreamReceivedEventArgs args)\n{\n    long bytesRemaining = args.ContentLength;\n    int bytesRead = 0;\n    byte[] buffer = new byte[65536];\n\n    using (MemoryStream ms = new MemoryStream())\n    {\n        while (bytesRemaining \u003e 0)\n        {\n            bytesRead = args.DataStream.Read(buffer, 0, buffer.Length);\n            if (bytesRead \u003e 0)\n            {\n                ms.Write(buffer, 0, bytesRead);\n                bytesRemaining -= bytesRead;\n            }\n        }\n    }\n\n    Console.WriteLine(\"Stream received from server: \" + Encoding.UTF8.GetString(ms.ToArray())); \n}\n```\n\n## Specifying a Client GUID\n\nIf you wish to specify a client's GUID, you can modify ```WatsonTcpClient.Settings.Guid``` prior to calling ```WatsonTcpClient.Connect()```.\n\n```csharp\nWatsonTcpClient client = new WatsonTcpClient(\"127.0.0.1\", 9000);\nclient.Events.ServerConnected += ServerConnected;\nclient.Events.ServerDisconnected += ServerDisconnected;\nclient.Events.StreamReceived += StreamReceived; \nclient.Settings.Guid = Guid.Parse(\"12345678-1234-1234-123456781234\");\nclient.Connect();\n```\n\n## Troubleshooting\n\nThe first step in troubleshooting is to implement a logging method and attach it to ```Settings.Logger```, and as a general best practice while debugging, set ```Settings.DebugMessages``` to ```true```.\n\n```csharp\nclient.Settings.DebugMessages = true;\nclient.Settings.Logger = MyLoggerMethod;\n\nprivate void MyLoggerMethod(Severity sev, string msg)\n{\n    Console.WriteLine(sev.ToString() + \": \" + msg);\n}\n```\n\nAdditionally it is recommended that you implement the ```Events.ExceptionEncountered``` event.\n\n```csharp\nclient.Events.ExceptionEncountered += MyExceptionEvent;\n\nprivate void MyExceptionEvent(object sender, ExceptionEventArgs args)\n{\n    Console.WriteLine(args.Json);\n}\n```\n\n## Disconnection Handling\n\nThe project TcpTest (https://github.com/jchristn/TcpTest) was built specifically to provide a reference for WatsonTcp to handle a variety of disconnection scenarios.  The disconnection tests for which WatsonTcp is evaluated include:\n\n| Test case | Description | Pass/Fail |\n|---|---|---|\n| Server-side dispose | Graceful termination of all client connections | PASS |\n| Server-side client removal | Graceful termination of a single client | PASS |\n| Server-side termination | Abrupt termination due to process abort or CTRL-C | PASS |\n| Client-side dispose | Graceful termination of a client connection | PASS |\n| Client-side termination | Abrupt termination due to a process abort or CTRL-C | PASS |\n| Network interface down | Network interface disabled or cable removed | Partial (see below) |\n\nAdditionally, as of v4.3.0, support for TCP keepalives has been added to WatsonTcp, primarily to address the issue of a network interface being shut down, the cable unplugged, or the media otherwise becoming unavailable.  It is important to note that keepalives are supported in .NET Core and .NET Framework, but NOT .NET Standard.  As of this release, .NET Standard provides no facilities for TCP keepalives.\n\nTCP keepalives are NOT enabled by default.  To enable and configure:\n```csharp\nserver.Keepalive.EnableTcpKeepAlives = true;\nserver.Keepalive.TcpKeepAliveInterval = 5;      // seconds to wait before sending subsequent keepalive\nserver.Keepalive.TcpKeepAliveTime = 5;          // seconds to wait before sending a keepalive\nserver.Keepalive.TcpKeepAliveRetryCount = 5;    // number of failed keepalive probes before terminating connection\n```\n\nSome important notes about TCP keepalives:\n\n- Keepalives only work in .NET Core and .NET Framework\n- ```Keepalive.TcpKeepAliveRetryCount``` is only applicable to .NET Core; for .NET Framework, this value is forced to 10\n\n## Disconnecting Idle Clients\n\nIf you wish to have WatsonTcpServer automatically disconnect clients that have been idle for a period of time, set ```WatsonTcpServer.IdleClientTimeoutSeconds``` to a positive integer.  Receiving a message from a client automatically resets their timeout.  Client timeouts are evaluated every 5 seconds by Watson, so the disconnection may not be precise (for instance, if you use 7 seconds as your disconnect interval).\n\n## Donations\n\nIf you would like to financially support my efforts, first of all, thank you!  Please refer to DONATIONS.md.\n\n## Version History\n\nPlease refer to CHANGELOG.md for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdotnet%2Fwatsontcp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdotnet%2Fwatsontcp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdotnet%2Fwatsontcp/lists"}