【问题标题】:tcpServer: How to send something and close the TCP connection afterwardstcpServer:之后如何发送一些东西并关闭 TCP 连接
【发布时间】:2014-03-25 10:37:59
【问题描述】:

我在我的 C# 应用程序中使用tcpServer:-

http://www.codeproject.com/Articles/488668/Csharp-TCP-Server

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

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

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

现在,当我执行此代码时,它会在向客户端发送文本之前关闭连接。

请帮我弄清楚我怎样才能达到同样的效果。

【问题讨论】:

  • 问题是,当我执行这段代码时,它会在向客户端发送文本之前关闭连接。
  • 是要正常关闭连接还是要强制客户端异常断开连接?
  • 正常关闭连接绝对是可取的
  • 那你为什么要调用forceDisconnect而不是正常关闭连接呢?

标签: c# sockets tcp


【解决方案1】:

试试这个

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

【讨论】:

  • 2 秒够吗?我正在寻找一个可以关闭连接的事件。
猜你喜欢
  • 2014-05-28
  • 2016-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-03
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多