question

Subazzz-3626 avatar image
0 Votes"
Subazzz-3626 asked ·

Dispose Stream socket listener in UWP

I have implemented two apps to run as server and client using stream sockets. It shares files from server app to multiple client apps when user is clicked on sharing option in Server app. I need to close sockets and socket listener when each operation is done. Sockets can be closed when each operations are competed.
There can be a scenario, Server app share only one file for the day. So I need to close the stream socket listener also.

What is best place to close the stream socket listener? Is there any best practice to follow.

Thanks in advance.

windows-uwp
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

NicoZhu-MSFT avatar image
0 Votes"
NicoZhu-MSFT answered ·

What is best place to close the stream socket listener? Is there any best practice to follow.

In general, we often make Dispose method for socket tool class, we could call StreamSocket.Dispose() then call StreamSocketListener.Dispose() at same time we need also to remove ConnectionReceived event handler

 public async override void Dispose()
 {
    clientSocket.Dispose();
      
     Listener.ConnectionReceived -= OnConnection;
     Listener?.CancelIOAsync();
     Listener.Dispose();
     Listener = null;
 }
· 6 · Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I have two separate apps for Server and Client. I can Dispose the socket from client side when data is read. As there can be many devices, when should I Dispose stream socket listener from Server side?

0 Votes 0 ·

sure, you need get all client sockets and dispose all them, we often save all the client sockets in the list and foreach it.

     foreach (var clientSocket in ClientSockets)
     {
         clientSocket.Dispose();
     }
     ClientSockets.Clear();
     ClientSockets = null;
0 Votes 0 ·

I need to dispose stream socket listeners. Not client sockets. I need to know what is the right moment to dispose the stream socket listeners as there can be multiple connections.

0 Votes 0 ·
Show more comments