alchemical
alchemical

Reputation: 13985

Which .Net component should be used for tcp/ip sockets communication?

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.

Upvotes: 3

Views: 3605

Answers (5)

jw33
jw33

Reputation: 253

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

Upvotes: 3

Eric Nicholson
Eric Nicholson

Reputation: 4123

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.

Upvotes: 1

user152800
user152800

Reputation: 126

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)

Upvotes: 8

Spencer Ruport
Spencer Ruport

Reputation: 35117

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

Upvotes: 1

Related Questions