Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert between Socket and TcpClient objects?

Here's another C#/.NET question based merely on curiousity more than an immediate need ...

If you had a Socket instance and you wanted to wrap it in the higher-level TcpClient class, is that possible and how would you do it?

Conversely if you have an instance of TcpClient, is it possible to get the underlying Socket?

like image 645
Neil C. Obremski Avatar asked Oct 14 '08 22:10

Neil C. Obremski


People also ask

What is TcpClient?

The TcpClient class provides simple methods for connecting, sending, and receiving stream data over a network in synchronous blocking mode. In order for TcpClient to connect and exchange data, a TcpListener or Socket created with the TCP ProtocolType must be listening for incoming connection requests.

How do I close TcpClient?

You have to close the stream before closing the connection: tcpClient. GetStream(). Close(); tcpClient.

What is host Contoso com?

This code for the client will connect to that server (supposedly host.contoso.com will be the name of the server in your particular case most likely will be the IP of your computer or the IP of the computer were you are running your server on).


1 Answers

If you had a Socket instance and you wanted to wrap it in the higher-level TcpClient class, is that possible and how would you do it?

Socket socket = ...;
TcpClient client = new TcpClient();
client.Client = socket;

Conversely if you have an instance of TcpClient, is it possible to get the underlying Socket?

Get the underlying Socket using TcpClient.Client property.

like image 135
Jorge Ferreira Avatar answered Oct 09 '22 09:10

Jorge Ferreira