Giter Site home page Giter Site logo

chronoxor / netcoreserver Goto Github PK

View Code? Open in Web Editor NEW
2.5K 90.0 533.0 20.13 MB

Ultra fast and low latency asynchronous socket server & client C# .NET Core library with support TCP, SSL, UDP, HTTP, HTTPS, WebSocket protocols and 10K connections problem solution

Home Page: https://chronoxor.github.io/NetCoreServer

License: MIT License

C# 97.42% HTML 1.50% Batchfile 0.60% Shell 0.27% CSS 0.03% JavaScript 0.18%
low-latency performance async tcp-server tcp-client udp-server udp-client socket-server socket-client http

netcoreserver's People

Contributors

alexlaguta avatar asheroto avatar cfhxqa avatar chronoxor avatar darxis avatar eieneika 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  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

netcoreserver's Issues

HTTPS and WSS on same port

Couldn't see anything in the documentation about this.
Is it possible to run a HTTPS server and WSS on the same port but under different directories, or would you need to use another server on top to accomplish that?

.NET Framework cross compatibility?

Wondering if there's a way to have this target both as many libraries do. We're in the process of transitioning to Core but would like to use this in our Framework 4.6 app in the meantime if possible.

Thanks!

tcp stick package

i create server for sending 200packages per 50 millionsecond.
then the problem of stick package happend.

eg:
1 package is
0x00 0x11 0x22 0x33 0x44 0x55

then client receive:
0x00 0x11 0x22 0x33 0x44 0x55 0x00 0x11

What is this Wizardry?

This isn't actually an issue with the code, and more with my difficulty in figuring out what's happening under the hood.

I'm designing an application that needs to run a telnet server - gonna be running a MUD game, hopefully! And I'd like to use this for the networking. So far so good, the server is up and echoing some text back as it's sent...

But I don't understand how this library works. What mechanisms are being used under the hood to achieve responsiveness? Is this running in its own thread for instance? Thread-per-connection? I've seen some usage of Events but I also saw a Thread.Yield() and lots of using System.Threading but I'm not seeing Threads actually CREATED anywhere either...

Since I need to design my main loop and everything related, I kinda need to know how this thing fits into the equation.

I'm a little new to C#, so...

Doesn't work in Unity

If we use this from Unity, the server detects a connection from the client, and the client can send data to the server, but the server can't send data to the client.

This happens with a TCP connection.

One Client

Hello dear how to send one message to a specific client ?

compatibility netcore3

NU1202: Package NetCoreServer 1.7.0 is not compatible with netcoreapp3.0

which core version are supported?

binding eth interface for multicast

I am trying to use code from UdpMulticastClient example.

When I provide following data in Program.cs:

            string listenAddress = "0.0.0.0";
            string multicastAddress = "239.8.100.0";
            int multicastPort = 8000;

I am able to receive data.

But when I provide correct IP address of my PC:

            string listenAddress = "192.168.238.60";
            string multicastAddress = "239.8.100.0";
            int multicastPort = 8000;

I am not able to receive data.

The question is:
how to bind the multicast to particular eth interface when I have more than one eth interface on my PC? Is it possible?

SslStream ShutdownAsync for Net 4.0 and line based protocol session handing.

Hi chronoxor,
Your TcpServer not using pre-buffer allocate strategy but there is no memory leak, it's a good server, but it using .Net default ThreadPool, it's cannot handle a lot of session, I think so.

I'm trying to compile your library (just some class) with .Net framework 4.0, but in SslSession and SslServer require ShutdownAsync to work, is there any alternative method to shutdown SslSession and SslServer asynchronous in .Net 4.0 ?

I want to develop a line based protocol program (like SMTP, POP3...) is there any idea for read line by line from your TcpSession class ?

Example Code UdpEchoServer

The example in the readme contains the UdpEchoServer which overrides void OnReceived(). The function parameters are missing the offSet Parameter.

protected override void OnReceived(IPEndPoint endpoint, byte[] buffer, long size)
    {
        Console.WriteLine("Incoming: " + Encoding.UTF8.GetString(buffer, 0, (int)size));

        // Echo the message back to the sender
        SendAsync(endpoint, buffer, 0, size);
    }

SslSession๏ผšData lost if sending continuously

if send new packet before previous packet is sent, the new packet will not send to client.

// in TrySend()
if (_sending)
                    return;

perhaps there should be a buffer manager, each send need a separate buffer to store data to send.

.net Framework 4.8?

Greetings.
I planned to use the netcoreserver in the current application im working on,
but cannot get it to work as VS cant find the "netstandart" reference.

i saw there was a framework branch already, any chance of getting an update to that one?

Azure Hosting model

Hi there,
first of all, thanks for NetCoreServer, great product.

What is your opinion on how to host a "NetCoreServer" on Azure? AppService? How to put multiple instances of the server?

I am curious about your opinion on this

regars,
Riccardo

Connect vs ConnectAsync behavior

Is there a difference of behavior from Connect and ConnectAsync?
How to reproduce:

In the Tcp or Ssl Chat Server/Client example change:

client.ConnectAsync();

to

client.Connect();

The client is now unable to receive any data from the server.
The client still connects as expected and is able to send data to the server though.

TLS 1.3 support

Hi, I see TLS 1.3 fails with "The client and server cannot communicate, because they do not possess a common algorithm", however CppServer works fine. Why?

Half of message

Why some times i receive only half of message? And how do i escape this?
All my messages should ends with $

As you can see first message is valid.
But second not. It is only half of my sended from server message

03:02:44.977:IConnection => OnReceived04.07.2019 15:02:44 eyJNZXNzYWdlSWQiOiI1Y2Y0MjkyNS02ZTMyLTQ3ZGItYTZlMi02NmY5ODI4OTQ0NWM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xzZSxcIlNlYXRPdXRIYW5kQ291bnRcIjowLFwiVGVtcE1pbmlTdGFja1dpdGhCZXRzRm9yU3RyZWV0XCI6MCxcIkNhcmRzXCI6W119LHtcIk1pblJhaXNlXCI6bnVsbCxcIklkXCI6XCIzMDU3ODViZi1lMTY1LTQ5Y2MtYWMxNi0yYWQyYWM1MmMyMjdcIixcIlVzZXJJZFwiOlwiMzFlZjFmZmEtZmI0NC00NzYyLWE1OGItMTU3NzFlMDQwNzFjXCIsXCJOaWNrbmFtZVwiOlwiRGV2VXNlcjNcIixcIkltYWdlVXJsXCI6bnVsbCxcIkNvdW50cnlcIjpudWxsLFwiVGFibGVQb3Np
buffer.Length=131600, offset=0, size=1400 {"Type":"IConnection","Level":"Debug"}

Calling the Buffer.Clear() only resets the offset and size and does not empty the underlying byte array.

Hello,

I am using the buffer class in my code and I came across some counter intuitive behavior. If I call the clear method I would expect the underlying data to be cleared in addition to the offset and size? Am I missing something? Unit test demonstrating the issue is below. Thanks.

[Fact]
public void GivenTheBufferIsClearedThenTheBufferDataShouldBeEmpty()
{
	var buffer = new Buffer(new byte[] { 0x01, 0x02, 0x03 });

	buffer.Clear();

	Assert.Empty(buffer.Data);
}

SSL Message Framing

I'm experiencing an issue with my implementation of message framing. I've read the other issue (#3) and practically did the same thing, but the server tends to crash at random times.

This is the code from my server.

private void SendData(string json) {
 byte[] data = Serialization.GroBuf.Serialize(json);

 byte[] sizeInfo = new byte[4];
 sizeInfo[0] = (byte) data.Length;
 sizeInfo[1] = (byte)(data.Length >> 8);
 sizeInfo[2] = (byte)(data.Length >> 16);
 sizeInfo[3] = (byte)(data.Length >> 24);

 SendAsync(sizeInfo);
 SendAsync(data);
}

private long _totalRead;
private bool _receivingMessage;
private int _messageSize;
private byte[] _fullMessage;
protected override async void OnReceived(byte[] buffer, long offset, long size) {
 if (!_receivingMessage && size == 4) {
  _messageSize |= buffer[offset + 0];
  _messageSize |= buffer[offset + 1] << 8;
  _messageSize |= buffer[offset + 2] << 16;
  _messageSize |= buffer[offset + 3] << 24;
  _receivingMessage = true;
  _fullMessage = new byte[_messageSize];
 } else if (_messageSize != 0) {
  Array.Copy(buffer, offset, _fullMessage, _totalRead, size); // System.ArgumentException: Destination array was not long enough. Check the destination index, length, and the array's lower bounds. (Parameter 'destinationArray')
  _totalRead += size;
  if (_messageSize != _totalRead) return;

  await HandleData(_fullMessage);

  _fullMessage = null;
  _messageSize = 0;
  _receivingMessage = false;
  _totalRead = 0;
 }
}

Any help is appreciated, thank you.

WPF/UWP/Windows

Hello! I tried your app and it seems to be exact what I need.
However, despite all your numerous examples, I can't seem to find one which uses WPF or UWP etc...
I wanted to know how to Start the server, check if the server is running and how to reconnect the server if it's down, check if the server got disconnected.

I know all these are in your examples but they all use the console. I am no expert into make use of those examples with a normal WPF app which would require, for e.g. an override of the OnConnected, OnDisconnected, OnReceived and OnError methods.

Could you please provide an example of the above functions and how to call them from my app?
for e.g.
int port = 1111;
var server = new ChatServer(IPAddress.Any, port);
server.OnError += ServerOnError;
txtServerStatus.Text = "Starting server...";
server.Start();
txtServerStatus.Text = "Done!";

void OnError(SocketError error)
{
txtServerStatus.Text = "Server caught an error with code {error}";
}
Thank you for helping out!

missing files

hey, files are missing, this repo only contains tcp server

Thread safety and sequencing

TcpServer::DisconnectAll()
New sessions can be added while the iterator returns currently registered sessions.
The server must first be told to stop accepting new connections, and wait for all currently processing connections to complete, then close all registered connections.
If the intent is to just disconnect what is currently connected (public function), then ok.

TcpSession::Disconnect()
Unregistering the event handlers before closing the socket connection will not give the session the ability to complete handling any pending data, e.g. complete reading received data.
Suggest, mark close pending with flag, close socket, any event handlers can look and see that close is pending and not re-issue next state, and then unregister event handlers.

TcpSession, TcpServer, BytesSent, BytesPending, BytesReceived
Counter values are incremented in a non-thread safe manner.
In one instance a send lock is taken, in other instances a non thread safe += operation is used.
With async handling multiple concurrent events can complete, and ordering inside handler is not deterministic.
Suggest using Interlock.Increment() or Interlocked.Add() methods.

Btw, symbols still not working, see comment added to issue.
Suggest; per the pattern used in SslX TcpX and UdpX, suggest deriving from base and override uniqueness vs. duplicating code and logic in each separate instance.

Load balancer

how would this perform behind a load balacer or hosted in Kubernetes?

Sessions are not explicitly deleted after disconnect

New sessions are created on connect, then registered in the dictionary, and unregistered on disconnect, but never explicitly disposed.

Are you relying on the GC to dispose of the sessions?
Is this really a good idea as they contain managed resources, i.e. socket and state objects.

Since it is not possible to "delete this" in C# (as far as I know), typical async implementations would mark sessions as stale, and periodically delete all stale sessions, or mark them for reuse, in a timer or cleanup loop.

Is there any way to bind local port of TcpClient ?

I have an embedded device run as a TCP server.
It is working on local port 4007 and ONLY accepted request from the client which bind on port 4009.
so I have to bind the local port of TcpClient.
Is there any way to do so?

Very low benchmarks results compared to results on README.md

I have run the benchmarks on my PC and experiencing very low results compared too the ones listed on the README.md. I am running the 1777931 commit
Environment:

CPU architecutre: Intel(R) Core(TM) i7-6820HK CPU @ 2.70GHz
CPU logical cores: 8
CPU physical cores: 4
CPU clock speed: 2.70 GHz
CPU Hyper-Threading: enabled
RAM total: 16 GB
RAM free: +-6 GB

OS version: Microsoft Windows 10 Pro (build 1909), 64-bit
OS bits: 64-bit
Process bits: 64-bit
Process configuration: Release

Here are my results for the SSL Multicast -c 100 test:

Server address: 127.0.0.1
Server port: 53698
Working clients: 100
Message size: 32
Seconds to benchmarking: 10

Clients connecting...Done!
All clients connected!
Benchmarking...Done!
Clients disconnecting...Done!
All clients disconnected!

Errors: 0

Total time: 11.389 s
Total data: 5.233 MiB <---------------------------
Total messages: 171306
Data throughput: 470.038 KiB/s <---------------------------
Message latency: 66.484 mcs <---------------------------
Message throughput: 15041 msg/s <---------------------------
Press any key to exit...

Compared to the ones listed on the README.md:

Server address: 127.0.0.1
Server port: 2222
Working clients: 100
Message size: 32

Errors: 0

Total time: 10.278 s
Total data: 66.540 MiB <---------------------------
Total messages: 2179997
Data throughput: 6.483 MiB/s <---------------------------
Message latency: 4.715 mcs <---------------------------
Message throughput: 212083 msg/s <---------------------------

As you can see, my tests benchmark results are more than 90% lower.

Could you please re-run the benchmarks again and post your results so that I can see if there is a problem with my environment or not? Commit 1777931

Issue using in .NetCore 2.1

Im not sure if im being silly but i can't use this is in .netcore 2.2/2.1/2.0 as the nuget package seems to target netstandard

Packets not being sent

Hi,

I'm writing a TCP server for a MMORPG Emulator project. We are using your library for our NetworkWrapping (thanks for your work btw)

We got a problem in our current software, sometimes, it happens that the player changes from map A to map B, there is almost nothing "active" on map B, just static objects, so we do send all the informations to the client and no more.
But, our problem is that, looks like the TCP socket is not being flushed correctly because nothing is received on the client side.

We tried to log every packets we received from different TCP clients, nothing were received in that special case

Do you have any recommendation about it ?
No special options on the server side, here is the TcpSession code :

public class WorldServerSession : TcpSession, INetworkSession
{
    private readonly IDecrypter _decrypter;
    private readonly IEncrypter _encrypter;
    private readonly NetworkInformations _networkClient;
    private readonly SessionManager _manager;
    private IPEndPoint _ip;

    public WorldServerSession(TcpServer server, IEncrypter encrypter, IDecrypter decrypter, NetworkInformations networkClient, SessionManager manager) : base(server)
    {
        _encrypter = encrypter;
        _decrypter = decrypter;
        _networkClient = networkClient;
        _manager = manager;
    }

    public RegionLanguageType Language
    {
        get => _networkClient.Language;
        set => _networkClient.Language = value;
    }

    public event EventHandler<string> PacketReceived;
    public IPAddress IpAddress => _ip.Address;

    public void SendPacketFormat(string packet, params object[] param)
    {
        SendPacket(string.Format(packet, param));
    }

    public void SendPackets(IEnumerable<string> packets)
    {
        if (IsDisposing)
        {
            return;
        }

        foreach (string packet in packets)
        {
            SendPacket(packet);
        }
    }

    public void DisconnectClient()
    {
        _manager.RemoveSession(this);
        Disconnect();
    }

    public bool IsDisposing { get; set; }

    public void SendPacket(string packet)
    {
        if (IsDisposing)
        {
            return;
        }

        try
        {
            var encrypted = _encrypter.Encode(packet).ToArray();
            var send = Send(encrypted);
            Logger.Log.Info($"[SENDING] {encrypted.Length} -> [send] {send}");
        }
        catch (Exception e)
        {
            Logger.Log.Error("SendPacket", e);
            DisconnectClient();
        }
    }

    public int SessionId
    {
        get => _networkClient.SessionId;
        set => _networkClient.SessionId = value;
    }

    protected override void OnConnected()
    {
        _ip = Socket.RemoteEndPoint as IPEndPoint;
    }

    protected override void OnDisconnected()
    {
        DisconnectClient();
    }

    protected override void OnReceived(byte[] buffer, long offset, long size)
    {
        if (IsDisposing)
        {
            return;
        }

        string buff = _decrypter.Decode(buffer.AsSpan((int)offset, (int)size));
        try
        {
            PacketReceived?.Invoke(this, buff);
        }
        catch (Exception e)
        {
            Disconnect();
            Logger.Log.Error("OnReceived", e);
        }
    }

    protected override void OnError(SocketError error)
    {
        Disconnect();
    }
}

Typical inactive map code :

session.SendPacket("mapobjectinfo 1");
session.SendPacket("mapobjectinfo 2");
session.SendPacket("mapobjectinfo 3");
session.SendPacket("mapobjectinfo 4");
session.SendPacket("mapobjectinfo 5");
session.SendPacket("mapobjectinfo 6");
session.SendPacket("mapobjectinfo 7");
session.SendPacket("mapobjectinfo 8");
session.SendPacket("mapobjectinfo 9");
session.SendPacket("mapobjectinfo 10");
session.SendPacket("mapobjectinfo 11");

How to limit the maximum connections in TcpServer.

Hi,

i am using TcpServer in my dotnet core console application and its running in port 5555. memory usage is getting increased frequently.

for example, i tried to run this application for a day and totally 280k messages sent/received (no multicast, only direct messages).

intially, the memory usage was 60 to 70 MB, after a day, it was 1,700MB. i checked my code for memory leakage issues, nothing is strange in my implementation, i am using DI for object initialization and all the unused things were disposed correctly.

still, the memory is getting high. i suspect that its due to number of con-current connections and its keep opened forever.

i want to force the client to getting disconnected after certain period of time and also want to limit the con-current connections to 500 or 1000.

kindly let me know, how can i implement this?

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.