使用ssl流保持打开套接字

时间:2016-11-10 07:19:48

标签: c# .net sockets ssl

我正在使用SSL Stream并为我需要的每个操作制作https soap请求。

我可以打开频道,而不是每次都发送证书,等待握手吗?

这是我正在使用的代码:

static void RunClient(string hostName, int port, X509Certificate2Collection certificates)
{
    // Create a TCP/IP client socket.
    // machineName is the host running the server application.
    TcpClient client = new TcpClient(hostName, port);
    Console.WriteLine("Client connected.");
    // Create an SSL stream that will close the client's stream.
    SslStream sslStream = new SslStream(
        client.GetStream(),
        false,
        ValidateServerCertificate);

    // The server name must match the name on the server certificate.
    try
    {
        sslStream.AuthenticateAsClient(hostName, certificates, SslProtocols.Default, true);
        DisplaySecurityLevel(sslStream);
        DisplaySecurityServices(sslStream);
        DisplayCertificateInformation(sslStream);
        DisplayStreamProperties(sslStream);
    }
    catch (AuthenticationException e)
    {
        Console.WriteLine("Exception: {0}", e.Message);
        if (e.InnerException != null)
        {
            Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
        }
        Console.WriteLine("Authentication failed - closing the connection.");
        client.Close();
        return;
    }
    // Encode a test message into a byte array.
    // Signal the end of the message using the "<EOF>".
    byte[] messsage = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
    // Send hello message to the server. 
    sslStream.Write(messsage);
    sslStream.Flush();
    // Read message from the server.
    string serverMessage = ReadMessage(sslStream);
    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.WriteLine("Server says: {0}", serverMessage);
    Console.ResetColor();
    // Close the client connection.
    client.Close();
    Console.WriteLine("Client closed.");
}

0 个答案:

没有答案