Giter Club home page Giter Club logo

simplesockets's Introduction

SimpleSockets

NuGet version

SimpleSockets is a .NET Standard 2.1 library with integrated framing and ssl support that provides an easy way to build fast and easy to use Tcp/Ip programs.

Table of Contents

Framing

Because Tcp/ip just sends a stream to a connected socket, it's impossible to know where a message starts and another one stops. To aid with easier messaging between sockets this library uses message framing. Wiki

Install

This project uses dotnetcore 2.1.
The latest version of the package can always be found on nuget.

PM> Install-Package SimpleSockets

or using .NET CLI

> dotnet add package SimpleSockets

Usage

Server

There are two different options of SimpleSocketListener

Server Description
SimpleSocketListener The base Listener class.
SimpleSocketTcpListener Server using Async calls without using Ssl.
SimpleSocketTcpSslListener Server using Async calls that uses a Ssl certificate to encrypt incoming & outgoing data.

To help authenticate connected clients on the server side, whenever a client connects to the server it will send an BasicAuth message -> this contains a GUID and the OSVersion the client is running. When the client sets 'EnableExtendedAuth' to true it will send a GUID, OSVersion, Pc Name and DomainName.

Wiki

Client

There are two different options of async client:

Client Description
SimpleSocketClient Base SimpleSocketClient class
SimpleSocketTcpClient Client using Async Calls without using Ssl.
SimpleSocketTcpSslClient An async client that uses an ssl certificate to encrypt incoming & outgoing data. By default the client does not need to authenticate. Only the server requires to be authenticated, the constructor has the option to require server and client authentication.

Wiki

Customization

I've added several classes that can be used to augment how the messaging of your sockets work.

Encryption

If you don't want to use Ssl, but don't want to send plaintext over the internet you can use the default Encryption added to the Library, which uses AES, the salt and key can be changed but have to correspond between client and server.
!! Warning ** This does not make your connection safe! If you're concerned with safety use Ssl !!

Custom Encryption
You can implement your own custom Encryption for client and server. Implement the interface IMessageEncryption and change the MessageEncryption of the client and server, if connected sockets are not using the same encryption it won't work.

Compression

By default folders will be compressed using ZIP compression before they are sent. All other types of messages won't be compressed. There are default classes for compressing, files, folders and Stream. Compression isn't always a good idea to use, if you're sending a small message there is a chance your message will actually increase in size when sending. (ByteCompressor is for all messages except files, folder).

Custom Compression
For folders: implement IFolderCompression and change the FolderCompressor of client, server.
For Files : implement IFileCompression and change the FileCompressor property of client, server.
For Stream : implement IByteCompression and change the ByteCompressor property of client, server.

Maintainers

@Cloet.

Contributing

Feel free to dive in! Open an issue or submit PRs.

Contributors

This project exists thanks to all the people who contribute.

License

MIT ยฉ Mathias Cloet

simplesockets's People

Contributors

benceroth avatar cloet avatar dependabot[bot] avatar jtone123 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simplesockets's Issues

CanAcceptConnections.WaitOne limits the new connections rate

Hello, I'm not really sure if this can be considered as a bug, but if I test the connection rate performance, after 209 connection without any wait, the server starts rejecting new connections.

In line 57 SimpleSocketTcpListener.cs, if you comment out "CanAcceptConnections.WaitOne();" the server happily accepts 15K new connections. Is there a better way to handle CanAcceptConnections functionality?

System.OverflowException: Arithmetic operation resulted in an overflow.

Describe the bug
I'm using TPL to send data back and forth as fast as possible with a 3 second wait time after 5 packets are sent. An exception is thrown within the first 30 seconds of running the program.

To Reproduce
Steps to reproduce the behavior:

Client side:

more:
 Parallel.For(0, 5, new ParallelOptions {
  MaxDegreeOfParallelism = 1
 }, async i => {
  packet = new Packet {
   command = "cmd",
    id = Guid.NewGuid(),

    meta = new List < object > {
     "data"
    }
  };

  await SocketClient.SendMessageAsync(JsonSerializer.Serialize(packet));
 });

await Task.Delay(TimeSpan.FromSeconds(3));
goto more;

Server side:
Look at my other comment, send something similar.

Expected behavior
Communication to flow freely with no exceptions.

Desktop (please complete the following information):

  • OS: Windows 10

Additional context
Perhaps instead of using Int32 we could move onto Int64?

[12: 22: 31 FTL] Unhandled exception thrown on socket client
Unhandled exception.System.Exception: Object reference not set to an instance of an object.
 -- - > System.NullReferenceException: Object reference not set to an instance of an object.
at SimpleSockets.Client.SimpleSocketTcpSslClient.Receive(IClientMetadata state, Int32 offset)
 -- - End of inner exception stack trace-- -
 at SimpleSockets.Client.SimpleSocketTcpSslClient.Receive(IClientMetadata state, Int32 offset)
at SimpleSockets.Client.SimpleSocketTcpSslClient.ReceiveCallback(IAsyncResult result)
at System.Threading.Tasks.Task. < > c. < ThrowAsync > b__139_1(Object state)
at System.Threading.QueueUserWorkItemCallbackDefaultContext.Execute()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
System.OverflowException: Arithmetic operation resulted in an overflow.
at SimpleSockets.Messaging.SimpleMessage.ReadData(Int32 receive)
at SimpleSockets.Messaging.SimpleMessage.ReadBytesAndBuildMessage(Int32 receive)
at SimpleSockets.Client.SimpleSocketTcpSslClient.ReceiveCallback(IAsyncResult result)```

How to add a Clientname

Hello,

In the IClientInfo interface there is a property "ClientName". How can I assign a value to this property?

Generics Send/Receive for typed messages

Is it possible to have generics interfaces to send and dispatch incoming messages? I mean, is there a way to register receivers for messages that are of a certain .net type?

MessageContract Messages disappear without trace using SSL and mono

I started a lot of tests today using the given examples to avoid other influences. I placed the server on a cloud server. The client is my local computer. Using SSL there is no MessageContract received. If I switch to SimpleSocketTcpClient everything works fine.

It seems there occures a problem when using MessageContracts if the server runs with mono.
If there is anything I can do to help debugging, please tell me!

Event Handler for MessageReceived(int id, string msg)

Hola, first and foremost thank you very much for contributing this codebase to the open-source community. It saved me a lot of frustration right off the bat. However, I'm now running into a issue that I believe is a bug unless I'm misunderstanding the id parameter of the MessageReceived event handler.

To Reproduce

  1. Open a Server Listener
  2. Open multiple client connections to the given Listener
  3. Set a break point on the internal void InvokeMessageReceived(int id, string text) function (called when (State.Header == "MESSAGE") evaluates as true)
  4. Have client 1 send multiple messages using SendMessage() to the server

The first message has an id of 1 as expected, but the second message has an id of 2. My understanding is that the id value passed should indicate which client id sent the message. If I've misunderstood the id parameter, please explain the proper use of it, and could you also explain how I might determine which client id sent the message to the Server Listener? Again I was thinking it would be the Id value inside the passed State.

Likewise, the MessageReceived event does not seem to be firing for additional clients. Only the first client seems to raise this event, despite it being attached to the Listener. I believe this is a bug but it's possible that I've modified something and that it may not be reproducible on your end. Please let me know what you are able to find.

Thanks for your time!

Server communication stops after client reconnect using ssl

Description
If SimpleSockets is used with SSL encryption first everything looks perfect. After clients disconnect and reconnect (restart client app) the server notices that client connected to server. Server also authenticate the client. From that moment on server ignores everything what client trys to send.

To Reproduce
Steps to reproduce the behavior:

  1. Edit Examples
    1a. Server.cs -> comment line 31 and uncomment line 32 ; insert a valid certificate
    Line looks like _listener = new SimpleSocketTcpSslListener(@"c:\wrk\a\srv2.pfx","test");
    1b. Client.cs --> comment line 30 and uncomment line 31; insert a valid certificate
    Line looks like: _client = new SimpleSocketTcpSslClient(@"c:\wrk\b\srv2.pfx", "test");

  2. Start Server

  3. Start Client

  4. Send Message from client (press M -> type message)

  5. Server receive message

  6. Stop Client App

  7. Start Client App

Server confirms client again:

Server authenticate certificate of client 1 .
Client 1 with IPv4 has connected to the server.

  1. Send Message from client (press M -> type message)
  2. Server does nothing...

Expected behavior
Server acts like on the first connection of client

Screenshots
not applicable

Desktop (please complete the following information):

  • Testet with MS Win 10 Pro and Ubuntu Linux 18.04 with Mono
  • Testet Nugget Version 1.0.1 and latest github source (November 25, 2019)

Example code for server does not work

Describe the bug
Example code for server does not work

To Reproduce
Steps to reproduce the behavior:

  1. Copy example of how to create server

Expected behavior
Compiles

BeginRead-Method Exception using SSL

Describe the bug
Today I tested your new nuget version 1.1.6 (old Version was 1.1.5 from git clone). I changed nothing on source code but there is thrown an Exception

31.01.2020 17:38:18 [Error] - Die BeginRead-Methode kann nicht aufgerufen werden, wenn ein anderer read-Vorgang ansteht.

31.01.2020 17:38:18 [Debug] - Die BeginRead-Methode kann nicht aufgerufen werden, wenn ein anderer read-Vorgang ansteht.

bei System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
bei System.Net.Security._SslStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback asyncCallback, Object asyncState)
bei System.Net.Security.SslStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback asyncCallback, Object asyncState)
bei SimpleSockets.Server.SimpleSocketTcpSslListener.Receive(IClientMetadata state, Int32 offset)
31.01.2020 17:38:18 [Error] - Server Error: Die BeginRead-Methode kann nicht aufgerufen werden, wenn ein anderer read-Vorgang ansteht.

31.01.2020 17:38:18 [Warn ] - Stack Trace follows:
bei System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
bei System.Net.Security._SslStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback asyncCallback, Object asyncState)
bei System.Net.Security.SslStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback asyncCallback, Object asyncState)
bei SimpleSockets.Server.SimpleSocketTcpSslListener.Receive(IClientMetadata state, Int32 offset)
31.01.2020 17:38:18 [Info ] - Client ID 1 getrennt: Remote-IP 127.0.0.1 auf Remote-System
31.01.2020 17:38:18 [Debug] - Client ID 1 mit Remote-IP 127.0.0.1 auf Remote-System was removed from client list
31.01.2020 17:38:18 [Debug] - [ListenerLOG: ]Closing socket from client with id:1 and Guid:

To Reproduce
Steps to reproduce the behavior:
SSL

Expected behavior
should work as 1.1.5

Screenshots
not applicable

bug in NetCore.Console.Client when sending object

when running NetCore.Console.Client and connecting to NetCore.Console.Server
there is a list of option of what to send to the server
when an object by pressing O it sends the object but the server doesnt recognize the object as person
but it recognize the object as :
"Received an object of type = Newtonsoft.Json.Linq.JObject"

and the code in
if (obj.GetType() == typeof(Person))
is always false since its not the type of person but as Newtonsoft.Json.Linq.JObject

[Feature Request] Disconnect Idle Clients

Is your feature request related to a problem? Please describe.
Implement a feature to disconnect idle clients in SimpleSocketListener base class.

Describe the solution you'd like
Disconnect idle clients in X seconds

Describe alternatives you've considered
Packets that update a dictionary of the last time the keep-alive packet was sent (my own keep-alive packet)

Additional context
N/A

Adding a few more basic commands to the server

Is your feature request related to a problem? Please describe.
Yes. My project is based around the restart function of the server, aka after the .StartListening(), it would be great to have a .StopListening() method. (Would be great if this feature could also be implemented on the client too)

Describe the solution you'd like
Implementing a .StopListening() function and a .StopClient() function.

Additional content
It would also be great if the server could "kick" a client by disconnecting it, making the disconnect happen on the client side is less secure, would also help when the server is doing the .StopListening() function to "kick" all connected clients.

Thanks for reading ๐Ÿ˜„

SendMessageAsync

Hi, I have a question.

On client Part:
When I try to set "close parameter" of SendMessageAsync method, to true.
Is thrown this exception:
Exception thrown: 'System.ObjectDisposedException' in System.dll ("Cannot access a disposed object.") | System.ObjectDisposedException

This behavior isn't implemented?
How to fix it?
Thanks.

Port to .net Standard

As far as i can see there wouldn't be any issue to change the target framework to .net standard 2.0. I just tried it (new .net standard project, copy/paste your code) and the only line to change is
using System.Diagnostics.Eventing.Reader;
in AsyncClientServer.Server.AsyncSocketListener which is a unused using.
=> Shouldn't be much work (if you want, i can do it too, just wanted to know, if you would accept it).

As Microsoft is going to dump the .net framework as we know it, this would future prove this code and make it multi platform too.

Events not triggered

Describe the bug
Events do not trigger

To Reproduce
Steps to reproduce the behavior:

  1. Create a project with framework 4.7.2
  2. Create a SimpleSocketTcpClient
  3. Bind events (AuthFailed / AuthSuccess for exemple) and send console writeline to test
  4. Start the client
  5. Events do not trigger

Expected behavior
Events being triggered

Desktop

  • OS: Windows 10
  • .NET 4.7.2 framework

Additional context
I tried 4 events (AuthFailed / AuthSuccess) & (ServerConnected & ServerDisconnected)
Only ServerConnected is working.
When my server is down and trying to connect to it with AuthFailed event nothing is triggered.

Thanks for your help! I love your library (I was looking for one which is simple to use) Thanks :)

My code:
public MainWindow() {
InitializeComponent();

        Start();

    }

    private void Start() {

        // Initialization
        SimpleSocketClient client = new SimpleSocketTcpClient();

        // Events
        client.AuthFailed += ClientOnAuthFailed;
        client.AuthSuccess += ClientOnAuthSuccess;

        // Start
        Console.WriteLine("Connecting...");
        client.StartClient("127.0.0.1", 1000);

    }

    private void ClientOnAuthFailed() {
        Console.WriteLine("Failed to authenticate.");
    }

    private void ClientOnAuthSuccess() {
        Console.WriteLine("Authenticated with success.");
    }

`

listener.StartListening(ip, port); doesn't start the Server

Description
When trying to create a TcpServer the server doesn't start or doesn't give an error

Steps to reproduce the behavior:
devenv_grnPE9e1oJ

Expected behavior
Server should start and client should be able to connect

Desktop:
Windows 10
Visual Studio 2019

Recognizing when the client fails to connect to the server

Is your feature request related to a problem? Please describe.
It would be nice to have a Client.OnConnectionFailure event so we could make it stop reconnecting or add other stuff

Describe the solution you'd like
Like mentioned above the addition of a Client.OnConnectionFailure event handler would be it

Describe alternatives you've considered
I could make the reconnect timer 0 and then manually close/dispose the client but then I would have to keep declaring it in order to reuse it

Additional context
I have been learning how to code by myself so if I am missing something please let me know, thanks in advance :)

Use in Winforms

Hi, I downloaded the new version and I noticed that if you try to use the files in Winforms it contains the following errors in compilation:

  1. The name 'ZipFile' does not exist in the current context.
  2. The type or space name of the name 'ZipArchive' was not found.

In the previous version using Winforms returned no error.

Overload SimpleSocketTcpSsl Constructor to provide Certificate directly

In a current project I need to provide the certificate content from string. Writing the certificate content into a file and load it again is just bugy...

So I would be very happy if a SimpleSocketTcpSsl Constructor provides the possibility to do that. Providing an X509Certificate2 Object to Constructor would be imho just as good as providing the content as sting.

Adding proxy support

Hello Cloet, I'm creating this issue not because I have a problem with your library (which is awesome by the way, and even the most complete one ^^), but because I have a request for an addition

I wanted to ask you if it was possible to add a small option, which would be the support of proxies.
I don't know much about networking, so I don't know if it's possible with TCP/UDP.
But if it's possible it would be great if it could be implemented! :)

And thanks again for your library, with the rewrite it will be even better :)
Goodbye! ^^

StartListening Problem.

Hi, if i use this for start the server:
"string ip = "192.168.1.177";
int port = 1234;
listener.StartListening(ip, port);"
In the file "AsyncSocketListener.cs" on line 54 return this exception: System.IndexOutOfRangeException: 'index was outside the bounds of the array'

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.