• Stars
    star
    424
  • Rank 101,768 (Top 3 %)
  • Language
    C#
  • License
    MIT License
  • Created almost 6 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple wrapper for TCP client and server in C# with SSL support

supersimpletcp

SuperSimpleTcp

Simple wrapper for TCP client and server in C# with SSL support

NuGet Version NuGet

SuperSimpleTcp provides simple methods for creating your own TCP-based sockets application, enabling easy integration of connection management, sending, and receiving data.

I would highly encourage you to fully understand what message framing is and why it's important before using this library: https://blog.stephencleary.com/2009/04/message-framing.html

New in v3.0.x

  • Breaking change, allocation-free receive (thank you @joreg)
  • Configurable sync vs async for firing DataReceived events (thank you @TheNybbler)
  • More configurability around certificate validation checks (thank you @ATS-CE)
  • Better catch client timeouts during TLS establishment (thank you @ATS-CE)
  • Add NoDelay to settings (thank you @huangjia2107)
  • Fix for PollSocket method, thank you @zllvm @Energiz0r @Espen-Kalhagen-Element-Logic
  • Added server-side NoDelay property in settings, thank you @QTPah

Special Thanks

A special thanks to the community of people that have contributed to or otherwise improved this project!

@tinohager @u1035 @cmeeren @pha3z @opnop @kopkarmecoindo @simonhaines @matt1tk @lukeacat @exergist @maynardsi @sector13371 @loganwoodxyz @jwfxpr @IanPNewson @EGirardi @redrabbit007 @eatyouroats @joreg @CetinOzdil @tautvilis @ATS-CE @TheNybbler @huangjia2107 @zllvm @Energiz0r @Espen-Kalhagen-Element-Logic @MarkBreedveld @QTPah @olifer

Help or Feedback

Need help or have feedback? Please file an issue here!

Simple Examples

Server Example

using SuperSimpleTcp;

void Main(string[] args)
{
  // instantiate
  SimpleTcpServer server = new SimpleTcpServer("127.0.0.1:9000");

  // set events
  server.Events.ClientConnected += ClientConnected;
  server.Events.ClientDisconnected += ClientDisconnected;
  server.Events.DataReceived += DataReceived;

  // let's go!
  server.Start();

  // once a client has connected...
  server.Send("[ClientIp:Port]", "Hello, world!");
  Console.ReadKey();
}

static void ClientConnected(object sender, ConnectionEventArgs e)
{
  Console.WriteLine($"[{e.IpPort}] client connected");
}

static void ClientDisconnected(object sender, ConnectionEventArgs e)
{
  Console.WriteLine($"[{e.IpPort}] client disconnected: {e.Reason}");
}

static void DataReceived(object sender, DataReceivedEventArgs e)
{
  Console.WriteLine($"[{e.IpPort}]: {Encoding.UTF8.GetString(e.Data.Array, 0, e.Data.Count)}");
}

Client Example

using SuperSimpleTcp;

void Main(string[] args)
{
  // instantiate
  SimpleTcpClient client = new SimpleTcpClient("127.0.0.1:9000");

  // set events
  client.Events.Connected += Connected;
  client.Events.Disconnected += Disconnected;
  client.Events.DataReceived += DataReceived;

  // let's go!
  client.Connect();

  // once connected to the server...
  client.Send("Hello, world!");
  Console.ReadKey();
}

static void Connected(object sender, ConnectionEventArgs e)
{
  Console.WriteLine($"*** Server {e.IpPort} connected");
}

static void Disconnected(object sender, ConnectionEventArgs e)
{
  Console.WriteLine($"*** Server {e.IpPort} disconnected"); 
}

static void DataReceived(object sender, DataReceivedEventArgs e)
{
  Console.WriteLine($"[{e.IpPort}] {Encoding.UTF8.GetString(e.Data.Array, 0, e.Data.Count)}");
}

Connect With Retries

The ConnectWithRetries method on SimpleTcpClient can be used instead of Connect to continually attempt to establish connections with the server for a given period of time. Like Connect, ConnectWithRetries will throw a TimeoutException if it is unable to successfully establish a connection.

client.ConnectWithRetries(10000); // try for up to 10000 milliseconds

Additional Configuration Options

Both SimpleTcpClient and SimpleTcpServer have settable values for:

  • Logger - method to invoke to send log messages from either SimpleTcpClient or SimpleTcpServer
  • Settings.MutuallyAuthenticate - only used if SSL is enabled, demands that both client and server mutually authenticate
  • Settings.AcceptInvalidCertificates - accept and allow certificates that are invalid or cannot be validated
  • Keepalive - to enable/disable keepalives and set specific parameters (disabled by default)

SimpleTcpServer also has:

  • Settings.IdleClientTimeoutSeconds - automatically disconnect a client if data is not received within the specified number of seconds

Additionally, both SimpleTcpClient and SimpleTcpServer offer a statistics object under SimpleTcpClient.Statistics and SimpleTcpServer.Statistics. These values (other than start time and uptime) can be reset using the Statistics.Reset() API.

Local vs External Connections

IMPORTANT

  • If you specify 127.0.0.1 as the listener IP address, it will only be able to accept connections from within the local host.
  • To accept connections from other machines:
    • Use a specific interface IP address, or
    • Use null, *, +, or 0.0.0.0 for the listener IP address (requires admin privileges to listen on any IP address)
  • Make sure you create a permit rule on your firewall to allow inbound connections on that port
  • If you use a port number under 1024, admin privileges will be required

Testing with SSL

A certificate named simpletcp.pfx is provided for simple testing. It should not expire for a really long time. It's a self-signed certificate and you should NOT use it in production. Its export password is simpletcp.

Disconnection Handling

The project TcpTest (https://github.com/jchristn/TcpTest) was built specifically to provide a reference for SuperSimpleTcp to handle a variety of disconnection scenarios. The disconnection tests for which SimpleTcp is evaluated include:

Test case Description Pass/Fail
Server-side dispose Graceful termination of all client connections PASS
Server-side client removal Graceful termination of a single client PASS
Server-side termination Abrupt termination due to process abort or CTRL-C PASS
Client-side dispose Graceful termination of a client connection PASS
Client-side termination Abrupt termination due to a process abort or CTRL-C PASS
Network interface down Network interface disabled or cable removed Partial (see below)

Additionally, as of v2.1.0, support for TCP keepalives has been added to SimpleTcp, 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.

TCP keepalives are disabled by default. To enable them:

server.Keepalive.EnableTcpKeepAlives = true;
server.Keepalive.TcpKeepAliveInterval = 5;      // seconds to wait before sending subsequent keepalive
server.Keepalive.TcpKeepAliveTime = 5;          // seconds to wait before sending a keepalive
server.Keepalive.TcpKeepAliveRetryCount = 5;    // number of failed keepalive probes before terminating connection

Some important notes about TCP keepalives:

  • Keepalives only work in .NET Core and .NET Framework
  • Keepalives can be enabled on either client or server, but are implemented and enforced in the underlying operating system, and may not work as expected
  • Keepalive.TcpKeepAliveRetryCount is only applicable to .NET Core; for .NET Framework, this value is forced to 10
  • Your mileage may vary; please remember that these are managed by the underlying operating system and not by this library

Running under Mono

.NET Core is the preferred environment for cross-platform deployment on Windows, Linux, and Mac. For those that use Mono, SimpleTcp should work well in Mono environments. It is recommended that you execute the containing EXE using --server and after using the Mono Ahead-of-Time Compiler (AOT).

mono --aot=nrgctx-trampolines=8096,nimt-trampolines=8096,ntrampolines=4048 --server myapp.exe
mono --server myapp.exe

Version History

Please refer to CHANGELOG.md.

More Repositories

1

WatsonWebsocket

A simple C# async websocket server and client for reliable transmission and receipt of data
C#
260
star
2

DatabaseWrapper

Simple database wrapper for Microsoft SQL Server, MySQL, PostgreSQL, and Sqlite written in C# supporting dynamic query building and nesting using expressions.
C#
92
star
3

HttpServerLite

TCP-based user-space HTTP and HTTPS server, written in C#, with no dependency on http.sys.
C#
73
star
4

PuppyProxy

A simple HTTP proxy in C# including support for HTTP CONNECT tunneling
C#
56
star
5

Blobject

BlobHelper is a common, consistent storage interface for Microsoft Azure, Amazon S3 (and S3-compliant storage), and local filesystem written in C#.
C#
56
star
6

CavemanTcp

CavemanTcp is a simple TCP client and server providing callers with easy integration and full control over network reads and writes.
C#
53
star
7

Kvpbase

Scalable, simple RESTful object storage platform, written in C#
C#
52
star
8

Less3

Less3 is an S3-compatible object storage server that runs on your laptop, servers, just about anywhere!
C#
47
star
9

RestDb

RESTful HTTP/HTTPS server for Microsoft SQL Server, MySQL, and PostgreSQL
C#
44
star
10

SimpleUdp

SimpleUdp is a super simple way of building UDP clients and servers in C#.
C#
36
star
11

WatsonDedupe

Self-contained C# library for data deduplication using Sqlite
C#
35
star
12

IndexEngine

IndexEngine is a lightweight document and text indexing platform written in C#.
C#
34
star
13

Gatekeeper

Lightweight library in C# for implementing roles-based access control (RBAC). With Gatekeeper, you can define users, roles, resources, and permissions, and authorize requests.
C#
33
star
14

LoggingModule

Brain-dead easy C# class library for logging to syslog, console, and file
C#
29
star
15

Caching

Simple FIFO and LRU cache in C#
C#
27
star
16

SqliteHelper

Simple wrapper for Sqlite databases written in C#.
C#
27
star
17

WatsonSyslogServer

C# Syslog Server
C#
25
star
18

RestWrapper

RestWrapper is a simple C# class library to help simplify sending REST API requests and retrieving responses (RESTful HTTP and HTTPS)
C#
25
star
19

WatsonMesh

A simple mesh networking library in C# based on WatsonTcp
C#
24
star
20

WatsonORM

WatsonORM is a lightweight and easy to use object-relational mapper (ORM) in C# for .NET Core.
C#
22
star
21

S3Server

Emulated Amazon Web Services (AWS) Simple Storage Service (S3) server-side interface.
C#
21
star
22

WatsonCluster

A simple C# class using Watson TCP to enable a one-to-one high availability cluster.
C#
20
star
23

IpMatcher

C# library for maintaining a match list of IP addresses and networks and comparing inputs to see if a match exists.
C#
15
star
24

ContainerFS

Single-user self-contained file system written in C#
C#
15
star
25

LiteGraph

Lightweight graph database built using Sqlite
C#
15
star
26

RegexMatcher

Regex Matching Library in C#
C#
12
star
27

komodo

Komodo: C# Information storage, metadata, search, and retrieval platform
C#
11
star
28

StringSimilarity

Simple US-English String Similarity Score Calculator
C#
10
star
29

NetLedger

NetLedger is a simple, self-contained ledgering library for adding debits and credits, checking balances, and performing commits on pending entries.
C#
10
star
30

PQueue

Lightweight, persistent, thread-safe, disk-based queue written in C#
C#
10
star
31

SimpleServer

Simple C# RESTful web server using Watson Webserver.
C#
8
star
32

ClosestString

Simple static library to identify the closest string from a list, and its edit distance, based on a supplied input string.
C#
7
star
33

TaskHandler

A simple C# class library to help manage running a queue of tasks without relinquishing control.
C#
7
star
34

EmailWrapper

Simple email wrapper in C# for SMTP and Mailgun
C#
7
star
35

PythonSharp

Console wrapper for running Python scripts in C#
C#
6
star
36

AWSSignatureGenerator

A simple class library for generating AWS V4 signatures.
C#
5
star
37

uscale

uscale - HTTP/HTTPS Loadbalancer in C#
C#
5
star
38

PdfTextExtractor

A simple C# shell wrapper for the wonderful pdfplumber library in Python to extract text from .PDF files
C#
4
star
39

UrlMatcher

Simple URL matcher library allowing you to match based on explicit string or parameters
C#
4
star
40

DocumentTextExtractor

Simple C# library for extracting text and metadata from .docx, .pptx, and .xlsx files
C#
4
star
41

S3Lite

Lightweight Amazon S3 client without all the heft and dependency drag of the official library.
C#
4
star
42

SerializationHelper

SerializationHelper is a simple wrapper around System.Text.Json to overcome some of the common challenges developers face when using Microsoft's JSON library compared to the Newtonsoft.Json library.
C#
4
star
43

TcpTest

Test project to better handle TCP disconnects and failures in SimpleTcp, WatsonTcp, and BigQ.
C#
4
star
44

KeyGenerator

Simple program and class library to generate DNA codewords to be used as keys given a series of constraints.
C#
4
star
45

OpenAuditLog

Simple C# event library providing event persistence and allowing you to write your own emitters
C#
4
star
46

PythonLoader

Example using pythonnet to run Python from C# with or without virtual environments in Windows, Mac, or Linux
C#
4
star
47

SlidingWindow

SlidingWindow provides an interface to retrieve chunks from a byte array using a sliding window.
C#
4
star
48

Webhooky

Webhooky helps you add webhooks to your app, with simple classes and methods for managing rules, targets, events, retries, and status.
C#
4
star
49

PrettyId

Simple static method for generating IDs like those used by Stripe and other services
C#
3
star
50

RosettaStone

Backend server for DNA data storage Rosetta Stone initiative
C#
3
star
51

SendWithBrevo

A simple C# class library to help simplify sending emails using Brevo.
C#
3
star
52

GoogleMapsClient

I needed a simple way to parse addresses and resolve coordinates to an address. Plug in a Google Maps API key and you're all set.
C#
3
star
53

PerformanceStatistics

Library for capturing performance statistics from commonly-used performance counters. Currently only supports Windows.
C#
3
star
54

Timestamps

Simple class containing start time, end time, and total time.
C#
3
star
55

ArangoDBLite

Lightweight ArangoDB SDK written in C#
C#
3
star
56

KvpbaseCSharpSDK

C# SDK for kvpbase
C#
3
star
57

SendWithMailgun

Simple class library to send email using Mailgun.
C#
3
star
58

HtmlPageBuilder

Simple library that allows you to build HTML strings including head and body components
C#
3
star
59

HttpContextLite

Nothing to see here
C#
3
star
60

MusicLabeler

Just something simple to apply ID3 tags to MP3 files based on the filename structure.
C#
2
star
61

ChunkDecoder

Library for decoding chunk-transfer-encoded data, particularly from HTTP.
C#
2
star
62

WatsonFunction

Function as a service (FaaS) platform for .NET core functions written in C#
C#
2
star
63

NuGetPackTest

Just testing how to pack dependencies inside NuGet packages
C#
2
star
64

ExpressionTree

A simple library for creating an expression tree.
C#
2
star
65

WatsonWebsocketJs

Javascript client for Watson Websocket
JavaScript
2
star
66

CommonPrefixes

Evalutes a list of strings and returns a list representing common prefixes found within based on a given delimiter.
C#
2
star
67

SerializableDataTable

SerializableDataTable is a library providing an abstraction class that allows you to serialize and deserialize data to and from a DataTable instance.
C#
2
star
68

Keyval

1
star
69

NeverBounce

Simple library for validating email addresses using NeverBounce.
C#
1
star
70

PDictionary

PDictionary is a persistent dictionary that stores dictionary contents to a JSON file.
C#
1
star
71

WatsonDedupeUI

UI for WatsonDedupe library
C#
1
star
72

StripeWrapper

A simple C# library for Stripe charges and refunds
C#
1
star
73

EditDistance

A simple library to assist in understanding edit distance algorithms.
C#
1
star
74

Shelli

Shelli is a simple static class to run things in your shell, tested on both Windows and Ubuntu.
C#
1
star
75

Geocode

Simple Geocode Implementation using Google Maps API
C#
1
star
76

Inputty

Inputty is a simple library that helps simplify the process of getting input from the console.
C#
1
star
77

WatsonTcpTest

Simple test project for WatsonTcp.
C#
1
star
78

KeepaliveTest

Test project to test TCP keepalives
C#
1
star
79

PaigoDotNet

Simple C# library for using Paigo
C#
1
star
80

WatsonWebserverTest

C#
1
star
81

WatsonWebsocketTest

Simple test wrapper for WatsonWebsocket
C#
1
star
82

WatsonWindowsService

C#
1
star