侦听同一流(TCPClient/SSLStream)上的其他请求

本文关键字:SSLStream 请求 其他 TCPClient | 更新日期: 2023-09-27 17:49:53

所以我有一个基于使用 TCPClient 流并将其转换为 SSLStream 的客户端服务器模型,但每次客户端想要向服务器发送新内容时,它会打开一个新的 TCP 连接到服务器,因为服务器在最后结束连接。我将如何侦听来自同一流的其他请求?不知道怎么做,这就是为什么我在最后杀死溪流。抱歉,如果令人困惑,如果无法理解,我可以修改。谢谢!

public void ServerListen()
{
TCPListener Server = new TCPListener(IPAddress.Any, 8001);
while (true)
{
Server.Start();
TCPClient TempClient = Server.AcceptTCPClient();
HandleRequest NewRequest = new HandleRequest(TempClient); // Send to a data handler class and open a separate thread to allow for additional clients to connect
}
}

public class HandleRequest
{
TCPClient WorkingClient;
public HandleRequest(TCPClient TempClient)
{
WorkingClient = TempClient;
(new Thread(new ThreadStart(DoWork))).Start();
}
public static void DoWork()
{
// Do Something Here With Data From Client
ProvideResponse(SomeData);
}
public static void ProvideResponse(object Data)
{
SSLStream SecureStream = new SSLStream(WorkingClient, false); // Kill inner stream after creating a secure connection
SecureStream.AuthenticateAsServer(MyCertificate, false, SslProtocols.Tls, true);
XmlSerializer XS = new XMLSerializer(typeof(someclass));
someclass TempObject = new someclass(){ InnerData = Data};
if (SecureStream.CanWrite)
{
XS.Serialize(SecureStream, TempObject);
}
SecureStream.Close();
}
}

侦听同一流(TCPClient/SSLStream)上的其他请求

SslStream只是简单地包裹了另一个Stream。如果您呼叫AuthenticateAsServer()另一端应该AuthenticateAsClient(),从那时起,您可以通过SSL进行通信。如果任何一方调用此方法失败,则SslStream将引发异常。

如果关闭使用 leaveInnerStreamOpen 参数设置为 true 构造的SslStream,则可以直接通过基础流进行通信,就好像从未有过SslStream一样(您甚至可以在SslStream仍处于打开状态时直接向/从底层流发送和接收(。

在像HTTPS这样的典型场景中,客户端和服务器会在建立连接后立即启用SSL,并在连接期间继续使用它。没有什么能阻止您在请求/响应后关闭两端的SslStream,并为下一条消息重新创建一个 - 您只需要在客户端和服务器之间保持"ssl 状态"同步。

至于你的评论:

建立 TCP 连接后,只要双方保持连接,就可以发送和接收数据。例如:

TcpClient client = TcpListener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
while (true)
{
    int bytes = stream.Read(...);
    if (bytes == 0) 
    {
        // other side has disconnected
        stream.Close();
        break;
    }
    // add incoming data to buffer, process messages
    ...
}

这就像通过在你们互相展示的一张纸上写文字来与某人交谈——你只需继续在同一张纸上写字,另一方可以在你写的时候阅读。

如果您在请求/响应后关闭TcpClient并使用TcpListener.AcceptXxx()打开一个新,则会在每条消息后扔掉每张纸。

如果我是你,我会在没有SslStream包装器的情况下玩这些概念(使用 NetworkStream 类(,直到你觉得你在做正确的事情。可以添加SslStream层,而无需对使用 NetworkStream 的代码进行任何重大更改。