0

我有一些创建 TCP/IP (IPv4) 套接字并侦听传入连接的功能。

private string RunServer(string certificate)
    {
        string messageData = "";
        X509Certificate2 cert = new X509Certificate2(@"C:\a.p12", "qwerty");
        var listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 443);
        listener.Start();
        while (true)
        {
            var client = listener.AcceptTcpClient();
            var sslStream = new SslStream(client.GetStream(), false);
            try
            {
                sslStream.AuthenticateAsServer(cert,
                false, SslProtocols.Tls, true);
                messageData = ReadFromSslClient(sslStream, client);
            }
            finally
            {
                sslStream.Close();
                client.Close();
            }
        }
        return messageData;
    }

以及读取客户端测试消息的功能。发生错误的地方:

private static string ReadFromSslClient(SslStream sslStream, TcpClient client)
    {
        byte[] buffer = new byte[2048];
        var messageData = new StringBuilder();
        int bytes = -1;
        do
        {
            try{
                if (client.Connected)
                {
                    bytes = sslStream.Read(buffer, 0, 1);
                    messageData.Append(bytes);
                }
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
             }
            catch(System.NotSupportedException notSupportedException)
            {

            }
        } while (bytes != 0);

        return messageData.ToString();
    }

当我尝试将数据读取到缓冲区时,我看到 10054 错误并且 client.Connected 等于 false。

4

0 回答 0