0

TLDR;

What are the differences in functionality and intended usage between TcpListener.AcceptSocket(Async) and TcpListener.AcceptTcpClient(Async)? Specifically, is NetworkStream of particular note?

Full detail and background

I'm trying to get to grips with the .NET socket functionality in order to write a server which maintains persistent TCP-IP connections for 2-way communication with multiple clients over a pre-defined protocol.

Initially Google led me to MS' Asynchronous Socket Example, which is heavily featured in SO questions on the topic.

Digging deeper into questions and answers, I saw people recommend using TcpClient / TcpListener over Socket.

Now TcpListener has (blocking and asynchronous versions of) two methods: AcceptSocket and AcceptTcpClient. MS' documentation briefly suggests the latter is simpler and the former gives more control but doesn't explain why or how. I can see from AcceptTcpClient vs AcceptSocket and TCPClient vs Socket in C# the latter gives access to a NetworkStream via TcpClient while the former exposes Send / Receive methods on Socket but that doesn't really explain why one is preferred.

So what are the differences and how should one choose which to use? Are there use-cases each is designed for? Why do both exist?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • Basically what it comes down to is that `AcceptTcpClient` is a more specific/specialized function that returns the more specific `TcpClient` rather than the more generic `Socket` (of which `TcpClient` is an extension of). – gmiley Oct 17 '19 at 11:09
  • @gmiley I feel like my question already embodies the answer to that linked one... which says very little. The question the answer links doesn't go much further. It seemed to me like `NetworkStream` was a key difference but by that point I am lost. – Mr. Boy Oct 17 '19 at 11:26
  • `Socket` is a lower-level class than `TcpClient`, offering the same functionality. If you don't need the former, you can use the latter to do the same with less code. That's all there is to it. – CodeCaster Oct 17 '19 at 11:40
  • "if you don't need the former" - well my question asks why/when I would need the former – Mr. Boy Oct 17 '19 at 11:41
  • You would use `TcpClient` if you needed to do TCP specific operations, otherwise without that distinction it is merely a `Socket`. Similarly there is a `UdpClient` for UDP specific operations even though that is also just a `Socket` at heart. – gmiley Oct 17 '19 at 12:36

0 Answers0