创建StreamSocket以将TCP消息发送到不同的IP地址,并在处理StreamSocket时发出问题

时间:2015-12-11 16:59:29

标签: c# win-universal-app stream-socket-client

我正在开发用于Windows 10的Universal Apps,它需要TCP通信,我已经创建了一个通用类库,其中一个名为TCPCom的类实现了IDisposable接口。 TCPCom有一个send方法,它有以下代码。 TCPCom类的Dispose方法处理StreamSocket对象。

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));
    }
}

因此,在Universal Apps的表单中,我将TCPCom的对象声明为全局变量,并在发送按钮单击事件处理程序上创建新对象并调用send方法。如果在Send方法中发生错误,则send方法捕获异常并在表单上引发事件。

现在我不知道在哪里处理TCPCom对象,任何人都可以指出一个正确的方向,以便以适当的方式关闭/处置TCPCom对象。

1 个答案:

答案 0 :(得分:0)

使用DataWriter:

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

重要的是作家.Detach。如果你没有分离,那么在处理编写器时你将丢弃OutputStream。