2

I need to write a TCP client to communicate with a server. Looking at code samples (Socket, TcpClient?), I don't seem to be able to find anything which feels like a "modern" way to do approach this, given what I've seen elsewhere in my C# adventures.

I suppose specifically I was expecting to see Tasks and code like await socket.Connect(args), but instead I see callback-based async or BeginX methods...

What are my options, here? Do I just get on with it and work with something without TPL, or are there other approaches?

Many thanks!

ledneb
  • 1,371
  • 1
  • 13
  • 25
  • 1
    Take a look at this [SO answer](http://stackoverflow.com/a/12631467/745969). You can also take a look at Stephen Toub's [Awaiting Socket Operations](http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx) article on his blog. – Tim Jan 28 '16 at 18:41
  • All these samples are terrible. Never use sockets with the APM pattern now that await exists! Also, question whether you need to go async at all. Sync IO is simpler. – usr Jan 28 '16 at 20:34

1 Answers1

6

There's no TAP-based raw socket API, no. I believe that the BCL team took a look at the Socket class - which already supports a complete synchronous API and two complete asynchronous APIs - and decided that adding a third complete asynchronous API would just be too much.

It's easy enough to use Task.Factory.FromAsync to wrap the existing Begin/End methods. Personally, I like to do this with extension methods so they can be called more naturally.

But first you should take a step back and see if there's any way to avoid using raw sockets. In particular, see if SignalR is a possibility. Writing correct raw socket code is extremely difficult, and using a higher-level abstraction would be much easier.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • 1
    But not half as fun! This isn't anything mission critical - I'd really like to be somebody who *can* write tricky socket code so I figure it's a nice little project. Thanks for your tips here - and also for the help you haven't so directly given me with your various other writings online! – ledneb Jan 29 '16 at 22:14
  • 2
    @ledneb: In that case, I have a [TCP/IP FAQ](http://blog.stephencleary.com/2009/04/tcpip-net-sockets-faq.html) that may help you along. Good luck! – Stephen Cleary Jan 30 '16 at 02:39
  • I hadn't come across that, looks a really useful read. Thanks again Stephen :-) – ledneb Jan 30 '16 at 09:30