Coder Social home page Coder Social logo

ygoe / asynctcpclient Goto Github PK

View Code? Open in Web Editor NEW
148.0 12.0 36.0 34 KB

An asynchronous variant of TcpClient and TcpListener for .NET Standard.

C# 100.00%
dotnet dotnet-standard network tcp tcp-server tcp-client async async-await asynchronous networking

asynctcpclient's People

Contributors

mikebouck avatar ygoe 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

asynctcpclient's Issues

Async TcpClient use within .NETStandard 2 Xamarin Forms?

Hi,

I am working an a project that with following requirements

  1. Has to use TCP/IP to send and receive messages
  2. The messages are in form of byte[]
  3. I must have method like GetDataAsync() which will use your AsyncTcpClient to write asynchronously the message (send it to a server at an IP/Port) AND will then read response from that server
  4. Once entire response is received, the response will then be converted into a string
  5. The string will be parsed and used to create a List models which is then displayed in a ListView
  6. This is to be done using .NETStandard 2.0 Xamarin Forms application.

Based on above, is this library helpful in such situation?
By looking at the code, I see use of Console.Read/Write which is not something you do in mobile apps.

Much appreciated,

AsyncTcpClient.Dispose() causes "Network error: Software caused connection abort" when using PuTTY

I added your classes to my code and have to say: nice work. But i had a little issue with AsyncTcpClient:

My Environment:

  1. I start the AsyncTcpClient by using your example code of RunAsync2() of your demo application
  2. I only added "serverClient.Dispose();" as last line inside the ReceivedCallback, because I want the listener to close the connection after the reply was sent.

User Problem:
When using PuTTY to test the communication, the "serverClient.Dispose()" causes PuTTY to complain about a lost connection (Message Box "Network error: Software caused connection abort").

Code Problem:
When calling AsyncTcpClient.Dispose(), the underlying socket gets forcefully terminated without properly diconnecting it.

Solution:
Instead of
tcpClient?.Dispose();
use

if (tcpClient != null){
    if (tcpClient.Client != null){
        tcpClient.Client.Disconnect(false);
    }
    tcpClient.Close();
    tcpClient.Dispose();
}

Best Regards

Arnothar

How to wait for a transmission's completion?

Dear Developer,

Thank you for this project.
Although, for example, we have a code where:

... // Somehere in AsyncTCPClient's initialization
ReceivedCallback = (c, count) =>
{
    Console.WriteLine("2");
    response = c.ByteBuffer.Dequeue(count);
    if (responseLength + count <= int.MaxValue)
        responseLength += count;
    Console.WriteLine("3, responseLength = {0}", responseLength );
    return Task.CompletedTask;
}
...
ct1 = new CancellationTokenSource(1000); // 1000ms for a request timeout
t1 = this.asyncTCPClient.Send(new ArraySegment<byte>(data, 0, data.Length), ct1.Token);
if (ct1.IsCancellationRequested) // If connection or any answer timeout
{
    Console.WriteLine("Timeout");
}
else
{
    ct1 = new CancellationTokenSource(1000); // 1000ms for a response timeour
    Console.WriteLine("1");
    t1 = this.asyncTCPClient.WaitAsync(ct1.Token); // Wait for any response available
    Console.WriteLine("4, responseLength = {0}", responseLength);
}

And the output would be:

    1
    4, responseLength = 0 // It seems that WaitAsync does not wait while ByteBuffer dequeues.
    2
    3, responseLength = 41

Is it possible to force WaitAsync to wait while the full transaction would be completed?

How to send the same data from Server to ALL clients?

Thank you for your AsyncTcpClient Solution. It's very useful.

I'd like to send the same data from Server to ALL clients.
For example, in a window of Server App, Click Button then, send the same data to all connected clients. No needs ReceivedCallback.
I have tried to add AsyncTcpClient Classes to list , but I could not do it.
Could you help me?

Implement a byte array pool for DequeueInternal

Currently since we allocate a new byte array for every ByteBuffer dequeue we make, it may not be very efficient for high loaded server since it will increase gc by a lot.

Alternatively, a custom byte array pool can be implemented to handle this for performance reasons so that we do less allocations

Any thoughts on handling network disconnection such as cable unplugged?

The close callbacks does not seem to execute for example when unplugging the network cable.
Would be nice if it can.

ReceiveTimeout, SendTimeout do not help (Only for sync methods)
Its like the ReadAsync is stuck waiting for data?

Reducing Keep Alive to 5

// Reduce Keep Alive check time to 5 seconds. // https://social.technet.microsoft.com/wiki/contents/articles/39650.c-the-use-of-keep-alive-to-deal-socket-abnormal-disconnection-method.aspx uint dummy = 0; byte[] inOptionValues = new byte[System.Runtime.InteropServices.Marshal.SizeOf(dummy) * 3]; // Set keepalive on BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0); // Interval time between last operation on socket and first checking. example:5000ms=5s BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, System.Runtime.InteropServices.Marshal.SizeOf(dummy)); // After first checking, socket will check serval times by 1000ms. BitConverter.GetBytes((uint)500).CopyTo(inOptionValues, System.Runtime.InteropServices.Marshal.SizeOf(dummy) * 2); tcpClient.Client.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);

Or how can I check for socket error after SendAsync then kill the ReadAsync so that it attempts reconnection or exits runAsync?

Is there are particular design reason why you can't Dequeue without Array Copy?

Dequeue always performs an array copy and returns the bytes.

If consumer Peeks at the data, consumer now has the byte array. Consumer can follow up with a dequeue to remove the bytes from the buffer, but consumer does not necessarily need the byte array returned because consumer already has it.

It seems desireable to be able to Peek at byte buffer, and then Dequeue it without performing a needless array copy.

To me it makes sense to add a VoidDequeue method that allows dequeuing without return. Is there a particular reason this is not implemented?

Async Write and concurrency

Hello,

Thank you for sharing this promising library. I have a question regarding async write. Indeed, you don't provide a similar mechanism as what you do for reading.

As I understand the logic of your code, you pull asynchronously (but sequentially) every bytes that are available from the stream.

Why don't you chose to not provide such a buffer for writing the packets sequentially ad then pushing asynchronously all the packets to the (write) stream ? What about concurrency of several tight-loop calls to WriteAsync ?

Thanks,
Lionel

How to send message from server to all connected clients?

First of all I want to congratulate you on the excellent code.
I have a problem. How to implement sending a message from the server to all connected clients. I've tried to debug to understand but I'm a little lost
Thank you,
Alex

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.