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