Simple tcp server windows

SimpleTcp

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

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

  • If you need integrated framing, please use WatsonTcp (https://github.com/jchristn/WatsonTcp)
  • If you need discrete control over the number of bytes read from or written to a socket, please use CavemanTcp (https://github.com/jchristn/CavemanTcp)

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 v2.4.0

  • Breaking change, timeouts now use milliseconds instead of seconds (does not apply to keepalive settings)

Help or Feedback

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

Simple Examples

Server Example

using SimpleTcp;

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, ClientConnectedEventArgs e)
{
  Console.WriteLine("[" + e.IpPort + "] client connected");
}

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

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

Client Example

using SimpleTcp;

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, EventArgs e)
{
  Console.WriteLine("*** Server connected");
}

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

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

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(10); // try for up to 10 seconds

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

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 SimpleTcp 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 enabled by default.

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

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

Special Thanks

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

@u1035 @cmeeren @tinohager @pha3z @opnop @kopkarmecoindo @simonhaines @matt1tk @lukeacat @exergist @maynardsi

Version History

Please refer to CHANGELOG.md.

A simple way to make a TCP server and contains methods relating to conversions

Product

Compatible and additional computed target framework versions.

.NET

net5.0 was computed. 

net5.0-windows was computed. 

net6.0 was computed. 

net6.0-android was computed. 

net6.0-ios was computed. 

net6.0-maccatalyst was computed. 

net6.0-macos was computed. 

net6.0-tvos was computed. 

net6.0-windows was computed. 

net7.0 was computed. 

net7.0-android was computed. 

net7.0-ios was computed. 

net7.0-maccatalyst was computed. 

net7.0-macos was computed. 

net7.0-tvos was computed. 

net7.0-windows was computed. 

net8.0 was computed. 

net8.0-android was computed. 

net8.0-browser was computed. 

net8.0-ios was computed. 

net8.0-maccatalyst was computed. 

net8.0-macos was computed. 

net8.0-tvos was computed. 

net8.0-windows was computed. 

net9.0 was computed. 

net9.0-android was computed. 

net9.0-browser was computed. 

net9.0-ios was computed. 

net9.0-maccatalyst was computed. 

net9.0-macos was computed. 

net9.0-tvos was computed. 

net9.0-windows was computed. 

.NET Core

netcoreapp2.0 was computed. 

netcoreapp2.1 was computed. 

netcoreapp2.2 was computed. 

netcoreapp3.0 was computed. 

netcoreapp3.1 was computed. 

.NET Standard

netstandard2.0 is compatible. 

netstandard2.1 was computed. 

.NET Framework

net461 was computed. 

net462 was computed. 

net463 was computed. 

net47 was computed. 

net471 was computed. 

net472 was computed. 

net48 was computed. 

net481 was computed. 

MonoAndroid

monoandroid was computed. 

MonoMac

monomac was computed. 

MonoTouch

monotouch was computed. 

Tizen

tizen40 was computed. 

tizen60 was computed. 

Xamarin.iOS

xamarinios was computed. 

Xamarin.Mac

xamarinmac was computed. 

Xamarin.TVOS

xamarintvos was computed. 

Xamarin.WatchOS

xamarinwatchos was computed. 

  • .NETStandard 2.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Made the events actual events instead of properties and made this asynchronous

Skip to content

S

SimpleTCPServer

Loading

Microsoft на странице «Сведения о выпуске» объявила о начале массового распространения Windows 11 2024 Update (версии 24H2). Это означает, что теперь эта версия операционной системы доступна для всех пользователей на устройствах, соответствующих минимальным системным требованиям. Напомним, что релиз Windows 11 2024 Update состоялся 1 октября 2024 года.

Чтобы получить обновление до WIndows 11 версии 24H2, откройте приложение «Параметры», перейдите в раздел «Центр обновления Windows» и проверьте наличие обновлений. После этого на странице должен появиться блок «Windows 11, version 24H2 доступно». Обновление по-прежнему является необязательным, поэтому вы должны вручную согласиться на установку Windows 11 версии 24H2.

Обновление может не появиться в России и Республике Беларусь из-за геоблокировки со стороны Microsoft. Для решения проблемы попробуйте настроить DNS-сервер от Comss.ru по этой инструкции или включить VPN с любой европейской страной, после чего вновь проверьте наличие обновлений. Если дело было в геоблокировке, то обновление должно появиться.

Если после всех этих действий раздел так и не появился, то, вероятно, обновление для вашего устройства пока заблокировано из-за проблем с совместимостью. Когда Microsoft устранит проблему, блокировка будет убрана и обновление станет доступно для установки.

Также вы можете вручную обновиться до WIndows 11 версии 24H2 с помощью утилиты Media Creation Tool или ISO-образов. Подробнее можете прочитать в нашей статье по этой ссылке. Однако если обновление недоступно именно из-за проблем с совместимостью, то Microsoft не рекомендует производить обновление вручную, поскольку это может привести к серьёзным проблемам со стабильностью работы системы.

Информацию об известных проблемах в Windows 11 версии 24H2 вы можете найти на сайте Microsoft: https://learn.microsoft.com/.

A (very simple) TCP server which you can use from within a testing environment or,
if you’re really ambitious, for some other reason.

Download stats

«Some tastiness to add to your dev sandwich»

PeanutButter is a collection of projects which provide useful
bits of functionality that I’ve often had to re-use (and also
provides some concrete examples of usage). Sometimes I can even
be bothered to write about it at
http://davydm.blogspot.co.za/search/label/PeanutButter.

Inside, you’ll find, amongst other things:

  • Duck-typing for .NET (PeanutButter.DuckTyping)
    • rigid or fuzzy duck-typing, including the ability
      to wrap a dictionary with a strongly-typed interface,
      even if the starting dictionary is empty.
  • Randomisation utilities for testing with (PeanutButter.RandomGenerators)
    • Random Value Generators
      • Tests with random values are usually more useful because,
        if nothing else, after many runs, you’ve hit many test
        scenarios and often an edge case which would cause you
        production headaches pops out of the wood work. I prefer
        to test with random values wherever possible
      • In addition to the helpers in RandomValueGen which can
        be used to get randomised:

        • string values (arbitrary, alphabetic, or alphanumeric)
        • numeric values (decimal, long)
        • boolean values
        • datetime values
          there is also the GenericBuilder base which you can use
          as a very quick and easy way to create builders for
          complex types. These builders have the ability to generate
          randomised or directed objects.
  • Test utilities:
    • PeanutButter.TestUtils.Generic which allows easy TestCase
      scenarios for property get/set tests with PropertyAssert
      which allows easy comparison of properties by name or, indeed
      relative path from the objects provided
    • PeanutButter.TestUtils.MVC (sunset) which provides a JsonResultExtensions
      class to simplify testing MVC actions which return JsonResults
    • PeanutButter.MVC (sunset), which provides facades and interfaces to make
      script and style bundles testable
    • PeanutButter.TestUtils.Entity provides mechanisms for testing
      your EF-based project code against temporary databases
      so you can be sure that the code you deploy will work as expected.
      This library is supported by PeanutButter.TempDb, so you can test
      (out of the box) against LocalDb, Sqlite and SQLCE. You can also
      provide your own TempDb<> implmentation
  • Arbitrary utils
    • DecimalDecorator which provides relatively safe string/decimal
      interchange, irrespective of culture
    • XElementExtensions to make dealing with XElement text easier
  • On-the-fly HTTP server for testing when you simply need a WebRequest
    to work
  • TempDb implementations (LocalDb, SqlCe and Sqlite) so you can run
    tests which involve migrations and integration between your ORM
    and the actual db
  • WindowsServiceManagement
    • provides functionality for query of & interaction with win32
      services using the native Win32 api, exposed in an easy-to-use
      C# POCO
  • PeanutButter.DatabaseHelpers
    • provides builders for Select, Update, Delete and Insert SQL
      statements for legacy projects where you can’t (at least, not
      yet) get in an ORM. The builders are more testable and you can
      use compile-time constants for table/column names to help to
      harden your code against dev errors and code rot
    • provides OleDB database executors and a data reader builder
  • PeanutButter.ServiceShell
    • provides scaffolding for a polling win32 service: inherit
      from the ServiceShell class, configure name and interval
      and provide your custom logic in the RunOnce override
    • resultant services can install and uninstall themselves as
      well as be invoked for once-off runs from the commandline.
      The project also contains a simple, but effective log4net
      configuration for console and a log file
  • EmailSpooler.Win32Service
    • harnesses PeanutButter.ServiceShell to provide a generic
      SMTP email spooling service backed with a data store. You
      can (theoretically) use any database which Entity can connect
      to, though this project has only been tested against MSSQL
    • EmailSpooler.Win32Service.DB provides FluentMigrator and
      raw SQL script files for generating the required underlying
      data structures.

Barring the last item, none of these are stand-alone: they’re all
just building blocks which I’ve had to repeat and refine, so I
figure they may be of use to others. As far as possible, the code
should be under test, though some projects are more difficult to
unit test (eg the PeanutButter.WindowsServiceManagement project,
which was developed TDD-style but which would sometimes flake out
on tests because the windows service management would be hit too hard
or often. But it does work (:) And some are libraries to help with
testing, so you’ll soon find that they work as expected.

A shout out to:

Jetbrains Logo

The work on PeanutButter would have been a lot more effort without
ReSharper from JetBrains. The good people at JetBrains have provided
free licensing for all of their products for open-source projects like
this one. To learn more about JetBrains products, please [visit them](http://jetbrains.com)

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Музыка windows 7 error song
  • Активация офиса 2019 в windows 10 по телефону
  • Служба intel rst не работает windows 7 что делать
  • Рейтинг бесплатных плееров для windows 10
  • Обновить поиск windows 10