Question

I am using TcpClient For a simple example of Socket Connection.

when the client connects :

clientSocket.Connect("192.168.1.3", 8888);
label1.Text = @"connecting...";

The client have to send me some data to the server (an english word), the server will then process that data, and return the result (definition of that word) ! after that the connexion must be stopped ! (when i say connexion needs to be stop i have no idea what i need to close and what i need to dispose)

anyway to stop which one of those should i use :

clientSocket.Client.Shutdown(SocketShutdown.Both);
clientSocket.Client.Dispose();
clientSocket.GetStream().Close();
clientSocket.Close();

my first problem is that when i try to connect again to the server with the same client (reuse the clientSocket) it gives me this exception, and it marks the clientSocket :

Message=Cannot access a disposed object.
Object name: 'System.Net.Sockets.TcpClient'.
Source=System
ObjectName=System.Net.Sockets.TcpClient

my sec problem is : to inform the client that the server want him to stop the connexion, it send a string message : "$" ! so each time the client receive a message, it checks if it is "$", if yes ! it start closing... im sure there is a better way to do that, can you please help me, thank you.

Was it helpful?

Solution

From Socket.Close():

The Close method closes the remote host connection and releases all managed and unmanaged resources associated with the Socket.

This means that calling .Dispose() yourself prior to closing will result in the "Cannot access a disposed object" error since .Close() will try to dispose (and close) the already disposed object.

Solution is easy: don't call .Dispose() yourself and let .Close() handle it.

OTHER TIPS

In general, I will never call Dispose "after" calling Close on an object. As an API user, I would just be calling Dispose and expect the API to do the right things for me.

The using(IDisposable) pattern is there for a reason! When using that, you are not concerned about any managed/unmanaged resource leaks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top