views:

303

answers:

5

We need to talk to another system that wants to communicate to us via raw tcp/ip socket communication. What would be the appropriate .Net object, if any, to use for this?

If you know of a 3rd party component, open source component, etc., that you think is better to use, please feel free to mention that as well.

+2  A: 

System.Net.Sockets.Socket

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx

Daniel A. White
`TcpClient` should always be used in favour of `Socket` as it wraps much of the functionality related to TCP communication. There's really no point re-inventing it yourself.
Noldorin
+1  A: 

The TcpClient is the most common, though I prefer the Socket class myself. Either will work.

Spencer Ruport
+6  A: 

I would use TcpClient. It sits on top of Socket and is an abstraction upon Socket. TcpClient has GetStream which returns a Stream object. Then to read the stream you can simply use a stream reader.

For example:

tcpClient = new TcpClient(host, port)
                            {
                                ReceiveTimeout = readTimeout
                            };
            stream = tcpClient.GetStream();
            streamReader = new StreamReader(stream, Encoding.ASCII);
            streamWriter = new StreamWriter(stream, Encoding.ASCII)
                               {
                                   AutoFlush = true
                               };

            return this;

Which then allows (snippet):

streamReader.Read(myReadBuffer, 0, myReadBuffer.Length)

+1  A: 

Socket & TCPClient are both pretty easy to manage and efficient. They'll definitely do what you need. There are a variety of good reasons to use the async modes of either.

Be warned that there are some threading issues. For instance, some of the async methods will terminate when the calling thread exits. There are a lot of very inefficient/bad .NET multi-threaded server examples out there too, so be careful. One last thing to watch out for is the exception handling. Often you just get a "SocketException" back and have to inspect it to figure out what really happened. It would be great if there were a few more derived SocketException classes that could be handled independently.

But don't let me discourage you, once you get your code implemented and working it'll continue to "just work" from then on.

Eric Nicholson
+1  A: 

Our company uses Dart Socket.net which basically wraps system.net.sockets.socket into really easy to use methods/components as well as having features of their own. I recommend them for windows form applications. They have lots of examples that come with their demos and have an active support forum that you can post questions and receive support/suggestions from.

Check them out at Dart.com http://www.dart.com/ptsknet.aspx

jwee