[Uwp] [C#] - 如何在发送消息后关闭TCP套接字[已解决] [英] [Uwp][C#] - How To close the TCP Socket after sent Message [solved]

查看:78
本文介绍了[Uwp] [C#] - 如何在发送消息后关闭TCP套接字[已解决]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,

我需要在发出消息后关闭我的TCP / IP套接字。  下面报告了我正在使用的代码。我看了很多与此相关的示例,但没有解决我的问题。

I need to close my TCP / IP Socket after sent out a message.  below reported the code that im using. I've looked a lot's of example related to that but nothing that is fixing my issues.

我看到有处理方法,但我不知道如何正确使用它。  可能有人帮助我吗?

I see that there is dispose method but I don't know how to use it correctly.  Could kindly someone help me ?

private async void SendTcp(string indirizzo, string messaggio)
        {
            try
            {
                //Create the StreamSocket and establish a connection to the echo server.
                Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();

                //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.
                Windows.Networking.HostName serverHost = new Windows.Networking.HostName(indirizzo);

                //Every protocol typically has a standard port number. For example HTTP is typically 80, FTP is 20 and 21, etc.
                //For the echo server/client application we will use a random port 1337.
                string serverPort = "1337";
                await socket.ConnectAsync(serverHost, serverPort);


                //Write data to the echo server.
                Stream streamOut = socket.OutputStream.AsStreamForWrite();
                StreamWriter writer = new StreamWriter(streamOut);
                string request = messaggio;
                await writer.WriteLineAsync(request);
                await writer.FlushAsync();
                 
                

                //Read data from the echo server.
                Stream streamIn = socket.InputStream.AsStreamForRead();
                StreamReader reader = new StreamReader(streamIn);
                string response = await reader.ReadLineAsync();

// here I would like close the socket
            }
            catch (Exception e)
            {
                //Handle exception here.            
            }
        }

谢谢

Andrea

推荐答案

大家好,

我已修复

with 

with 

using (writer)
                {
                    await writer.WriteLineAsync(request);
                    await writer.FlushAsync();
                    writer.Dispose();
                }

                socket.Dispose();

问候,

Andrea


这篇关于[Uwp] [C#] - 如何在发送消息后关闭TCP套接字[已解决]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆