none
Socket without blocking existing loop RRS feed

  • Question

  • Hey

    I have an application that is running as an infinite loop. I'm trying to be able to send and receive messages between this application and another application over network. I'v been looking at Async socket example https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example but I dont quite understand it. Im wondering if this is the best approuch or if I should be looking at something else?

    Regards

    Wednesday, January 16, 2019 7:20 AM

All replies

  • That code is demoing how to make async calls with a socket so it is a fine example. If you don't want to block then you would just need to modify the StartListening method that they provided. They have a loop so that: a) it will allow any # of connections and b) so the console app won't terminate. Adjust that logic to fit your needs and you're fine. There are also many, many other examples posted online on how to use Socket in .NET.

    I would recommend that you take a look at TcpListener/TcpClient instead though. Unless you are comfortable with socket programming these 2 types are designed to wrap a socket and make it easier to use them. There isn't any disadvantages to them and they handle some common things that you'd have to write code for if you used the socket directly. For TcpListener you'd use the -Async methods to work with tasks instead of BeginAccept but otherwise they work similar. Here's an older article on how you might use it in an async situation. There are other approaches as well.


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, January 16, 2019 2:46 PM
    Moderator
  • I wrote a blog post about this topic last month:

    http://geek-goddess-bonnie.blogspot.com/2018/12/event-driven-tcp.html

    I explain a few concepts and include downloadable working solutions. Take a look ...


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Wednesday, January 16, 2019 2:57 PM
    Moderator