Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# tcpServer:如何发送内容并在之后关闭TCP连接_C#_Sockets_Tcp - Fatal编程技术网

C# tcpServer:如何发送内容并在之后关闭TCP连接

C# tcpServer:如何发送内容并在之后关闭TCP连接,c#,sockets,tcp,C#,Sockets,Tcp,我正在使用我的C#app中给出的tcpServer:- 它有一个TcpServer类,可以打开一个端口并开始监听它。我通过TcpServer类提供的OnDataAvailable事件处理程序接收数据。问题是,客户端期望并依赖tcp服务器关闭连接 在关闭连接之前,(有条件地)我想将一些数据发送回客户端。 以下是我为了达到同样的目的而写的东西 static void myServer_OnDataAvailable(TcpServerConnection connection) { //.

我正在使用我的C#app中给出的
tcpServer
:-

它有一个
TcpServer
类,可以打开一个端口并开始监听它。我通过
TcpServer
类提供的
OnDataAvailable
事件处理程序接收数据。问题是,客户端期望并依赖tcp服务器关闭连接

在关闭连接之前,(有条件地)我想将一些数据发送回客户端。 以下是我为了达到同样的目的而写的东西

static void myServer_OnDataAvailable(TcpServerConnection connection)
{
    //...Some code...
    connection.sendData(someText);
    if (connection.verifyConnected())
    {
        connection.forceDisconnect();
    }
}
现在,当我执行这段代码时,它会在向客户端发送文本之前关闭连接

请帮我想一想怎样才能达到同样的效果。

试试这个

static void myServer_OnDataAvailable(TcpServerConnection connection)
{
    //...Some code...
    connection.sendData(someText);
    if (connection.verifyConnected())
    {
        connection.forceDisconnect();
    }
}
static void myServer_OnDataAvailable(TcpServerConnection connection)
{
    //...Some code...
    connection.sendData(someText);
    Thread.Sleep(2000);
    if (connection.verifyConnected())
    {
        connection.forceDisconnect();
    }
}

问题是,当我执行这段代码时,它会在向客户端发送文本之前关闭连接。您是想正常关闭连接,还是想强制客户端异常断开连接?当然最好是正常关闭连接,那么为什么您要调用
forceDisconnect
而不是正常关闭连接?2秒是否足够?我正在搜索可以关闭连接的事件。