Anna Jhaveri
Anna Jhaveri

Reputation: 93

Create StreamSocket to send TCP messages to different IP Address and issue on dispose the StreamSocket

I am developing Universal Apps for Windows 10 which requires TCP communications for which I have created a Universal Class Library, with a class called TCPCom which implements IDisposable interface. The TCPCom has a send method which has following code. The Dispose method of TCPCom class disposes the StreamSocket object.

public async Task Send(string ipAddress, string port)
{
    try
    {
        //The server hostname that we will be establishing a connection to. We will be running the server and client locally,
        //so we will use localhost as the hostname.
        HostName serverHost = new HostName(ipAddress);
        if (talkerSocket == null)
        {
            //Every protocol typically has a standard port number. For example HTTP is typically 80, FTP is 20 and 21, etc.            
            talkerSocket = new StreamSocket();
            await talkerSocket.ConnectAsync(serverHost, port);
            IsConnected = true;
        }

        //Write data to the echo server.
        Stream streamOut = talkerSocket.OutputStream.AsStreamForWrite();
        StreamWriter writer = new StreamWriter(streamOut);
        await writer.WriteLineAsync("test message");
        await writer.FlushAsync();
    }
    catch (Exception ex)
    {
        //invoke error event
        OnErrorOccurred(this, new ErrorEventArgs(ex));
    }
}

So on the form in Universal Apps, i am declaring an object of TCPCom as global variable and on send button click event handler i am creating new object and calling the send method. If an error occurs in Send method the send method catches the exception and raises an event on form.

Now what I dont know here is where to dispose the TCPCom object, can anyone point me a right direction in order to close/dispose the TCPCom object in appropriate way.

Upvotes: 0

Views: 505

Answers (1)

The Sharp Ninja
The Sharp Ninja

Reputation: 1041

Use DataWriter as such:

Stream streamOut = talkerSocket.OutputStream;
DataWriter writer = new DataWriter(streamOut);
writer.WriteString("test message");
await writer.StoreAsync();
writer.Detach();

The important thing is writer.Detach. If you don't detach, then you dispose of the OutputStream when writer is disposed.

Upvotes: 0

Related Questions