当前位置: 首页>>代码示例>>C#>>正文


C# SslStream.Write方法代码示例

本文整理汇总了C#中System.Net.Security.SslStream.Write方法的典型用法代码示例。如果您正苦于以下问题:C# SslStream.Write方法的具体用法?C# SslStream.Write怎么用?C# SslStream.Write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Security.SslStream的用法示例。


在下文中一共展示了SslStream.Write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: UploadFile

        protected WaUploadResponse UploadFile(string b64hash, string type, long size, byte[] fileData, string to, string contenttype, string extension)
        {
            ProtocolTreeNode media = new ProtocolTreeNode("media", new KeyValue[] {
                new KeyValue("hash", b64hash),
                new KeyValue("type", type),
                new KeyValue("size", size.ToString())
            });
            string id = TicketManager.GenerateId();
            ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] {
                new KeyValue("id", id),
                new KeyValue("to", WhatsConstants.WhatsAppServer),
                new KeyValue("type", "set"),
                new KeyValue("xmlns", "w:m")
            }, media);
            this.uploadResponse = null;
            this.SendNode(node);
            int i = 0;
            while (this.uploadResponse == null && i <= 10)
            {
                i++;
                this.pollMessage();
            }
            if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null)
            {
                WaUploadResponse res = new WaUploadResponse(this.uploadResponse);
                this.uploadResponse = null;
                return res;
            }
            else
            {
                try
                {
                    string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url");
                    this.uploadResponse = null;

                    Uri uri = new Uri(uploadUrl);

                    string hashname = string.Empty;
                    byte[] buff = MD5.Create().ComputeHash(System.Text.Encoding.Default.GetBytes(b64hash));
                    StringBuilder sb = new StringBuilder();
                    foreach (byte b in buff)
                    {
                        sb.Append(b.ToString("X2"));
                    }
                    hashname = String.Format("{0}.{1}", sb.ToString(), extension);

                    string boundary = "zzXXzzYYzzXXzzQQ";

                    sb = new StringBuilder();

                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.Append("Content-Disposition: form-data; name=\"to\"\r\n\r\n");
                    sb.AppendFormat("{0}\r\n", to);
                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.Append("Content-Disposition: form-data; name=\"from\"\r\n\r\n");
                    sb.AppendFormat("{0}\r\n", this.phoneNumber);
                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", hashname);
                    sb.AppendFormat("Content-Type: {0}\r\n\r\n", contenttype);
                    string header = sb.ToString();

                    sb = new StringBuilder();
                    sb.AppendFormat("\r\n--{0}--\r\n", boundary);
                    string footer = sb.ToString();

                    long clength = size + header.Length + footer.Length;

                    sb = new StringBuilder();
                    sb.AppendFormat("POST {0}\r\n", uploadUrl);
                    sb.AppendFormat("Content-Type: multipart/form-data; boundary={0}\r\n", boundary);
                    sb.AppendFormat("Host: {0}\r\n", uri.Host);
                    sb.AppendFormat("User-Agent: {0}\r\n", WhatsConstants.UserAgent);
                    sb.AppendFormat("Content-Length: {0}\r\n\r\n", clength);
                    string post = sb.ToString();

                    TcpClient tc = new TcpClient(uri.Host, 443);
                    SslStream ssl = new SslStream(tc.GetStream());
                    try
                    {
                        ssl.AuthenticateAsClient(uri.Host);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }

                    List<byte> buf = new List<byte>();
                    buf.AddRange(Encoding.UTF8.GetBytes(post));
                    buf.AddRange(Encoding.UTF8.GetBytes(header));
                    buf.AddRange(fileData);
                    buf.AddRange(Encoding.UTF8.GetBytes(footer));

                    ssl.Write(buf.ToArray(), 0, buf.ToArray().Length);

                    //moment of truth...
                    buff = new byte[1024];
                    ssl.Read(buff, 0, 1024);

                    string result = Encoding.UTF8.GetString(buff);
                    foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
//.........这里部分代码省略.........
开发者ID:RCOliveira,项目名称:WhatsAPINet,代码行数:101,代码来源:WhatsApp.cs

示例2: GetAuthTokenFromReqeustToken

        /// <summary>
        /// Make a request to get a valid access Token from the refresh token
        /// </summary>
        /// <returns>a valid access token from the refresh code request</returns>
        public GoogleOAuth2AccessToken GetAuthTokenFromReqeustToken()
        {
            byte[] contentAsBytes = null;
            int contentLength = 0;

            //Submit using TCP Protocol
            contentAsBytes = Encoding.ASCII.GetBytes(ContentBody);
            contentLength = contentAsBytes.Length;

            string header = BuildHeader(true, contentLength);
            byte[] headerAsBytes = Encoding.ASCII.GetBytes(header);

            TcpClient client = new TcpClient(Host, 443);
            Stream netStream = client.GetStream();
            SslStream sslStream = new SslStream(netStream);
            sslStream.AuthenticateAsClient(Host);

            sslStream.Write(headerAsBytes);
            sslStream.Write(contentAsBytes);
            GoogleOAuth2AccessToken token = new GoogleOAuth2AccessToken();

            StreamReader reader = new StreamReader(sslStream);

            int left;
            var quote = Convert.ToString(Convert.ToChar(34));
            while (reader.Peek() > 0)
            {
                string line = reader.ReadLine();
                if (line == null) break;

                left = line.IndexOf(": ") + 1;

                if (left > 0)
                {
                    var result = line.Substring(left).Replace(quote, "").Replace(",", "").Replace(":", "").Trim();

                    if (line.ToLower().Contains("access_token"))
                    {
                        token.access_token = result;
                    }
                    else if (line.ToLower().Contains("expires_in"))
                    {
                        token.expires_in = result;
                    }
                    else if (line.ToLower().Contains("token_type"))
                    {
                        token.token_type = result;
                    }
                    else if (line.ToLower().Contains("id_token"))
                    {
                        token.id_token = result;
                    }
                }
            }
            sslStream.Close();
            return token;
        }
开发者ID:blgorman,项目名称:DotNetGooglePIcasaUtility,代码行数:61,代码来源:GoogleRequestor.cs

示例3: processClient

        private void processClient(TcpClient client)
        {
            X509Certificate certificate = new X509Certificate("..\\..\\..\\Certificate\\Certificate.pfx", "KTYy77216");
            // SslStream; leaveInnerStreamOpen = false;
            SslStream stream = new SslStream(client.GetStream(), false);
            try
            {
                // clientCertificateRequired = false
                // checkCertificateRevocation = true;
                stream.AuthenticateAsServer(certificate, false, SslProtocols.Tls, true);
                Console.WriteLine("Waiting for client message ...");

                // Read a message from the client
                string input = readMessage(stream);
                Console.WriteLine("Received: {0}", input);

                // Write a message to the client
                byte[] message = Encoding.UTF8.GetBytes("Hello client, this is a message from the server :)<EOF>");
                Console.WriteLine("Sending message to client ...");
                stream.Write(message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                stream.Close();
                client.Close();
                return;
            }
            finally
            {
                stream.Close();
                client.Close();
            }
        }
开发者ID:bemk,项目名称:rhc,代码行数:34,代码来源:SslTcpServer.cs

示例4: Discover

        public ServiceEndPoint Discover(Uri remoteUri)
        {
            try
            {
                using (var client = CreateTcpClient())
                {
                    client.ConnectWithTimeout(remoteUri, HalibutLimits.TcpClientConnectTimeout);
                    using (var stream = client.GetStream())
                    {
                        using (var ssl = new SslStream(stream, false, ValidateCertificate))
                        {
                            ssl.AuthenticateAsClient(remoteUri.Host, new X509Certificate2Collection(), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false);
                            ssl.Write(HelloLine, 0, HelloLine.Length);
                            ssl.Flush();

                            if (ssl.RemoteCertificate == null)
                                throw new Exception("The server did not provide an SSL certificate");

                            return new ServiceEndPoint(remoteUri, new X509Certificate2(ssl.RemoteCertificate).Thumbprint);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HalibutClientException(ex.Message, ex);
            }
        }
开发者ID:BradBarnich,项目名称:Halibut,代码行数:28,代码来源:DiscoveryClient.cs

示例5: Discover

        public ServiceEndPoint Discover(ServiceEndPoint serviceEndpoint)
        {
            try
            {
                using (var client = CreateConnectedTcpClient(serviceEndpoint))
                {
                    using (var stream = client.GetStream())
                    {
                        using (var ssl = new SslStream(stream, false, ValidateCertificate))
                        {
                            ssl.AuthenticateAsClientAsync(serviceEndpoint.BaseUri.Host, new X509Certificate2Collection(), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false)
                                .GetAwaiter()
                                .GetResult();
                            ssl.Write(HelloLine, 0, HelloLine.Length);
                            ssl.Flush();

                            if (ssl.RemoteCertificate == null)
                                throw new Exception("The server did not provide an SSL certificate");

                            return new ServiceEndPoint(serviceEndpoint.BaseUri, new X509Certificate2(ssl.RemoteCertificate.Export(X509ContentType.Cert)).Thumbprint);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HalibutClientException(ex.Message, ex);
            }
        }
开发者ID:OctopusDeploy,项目名称:Halibut,代码行数:29,代码来源:DiscoveryClient.cs

示例6: RunClient

            public static string RunClient(string serverName,string activation_info,ref string buffer)
            {                                
                TcpClient client = new TcpClient(serverName,443);                
                SslStream sslStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null
                    );
              
                try
                {
                    sslStream.AuthenticateAsClient(serverName);
                }
                catch (AuthenticationException e)
                {   
                    if (e.InnerException != null)
                    {
                    }
                    client.Close();
                    Environment.Exit(-1);
                }

                byte[] messsage = Encoding.UTF8.GetBytes(activation_info + "\n<EOF>");                
                sslStream.Write(messsage);
                sslStream.Flush();               
                string serverMessage = ReadMessage(sslStream);                
                client.Close();                
                buffer = serverMessage;
                return serverMessage;
            }
开发者ID:rAbd0u,项目名称:iactivator,代码行数:31,代码来源:SslTcpClient.cs

示例7: runClient

        private void runClient()
        {
            TcpClient client = new TcpClient(server, port);
            Console.WriteLine("Client connected ...");

            // Create ssl stream
            SslStream stream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(validateServerCertificate), null);

            stream.AuthenticateAsClient(server);

            // write message to server
            byte[] output = Encoding.UTF8.GetBytes("Message from client :D<EOF>");
            stream.Write(output);
            stream.Flush();

            // read message from server
            string input = readMessage(stream);
            Console.WriteLine("Received: {0}", input);

            // close everything
            stream.Close();
            client.Close();
            Console.WriteLine("Client closed connection ...");
            // Press any key to continue ...
            Console.ReadKey();
        }
开发者ID:bemk,项目名称:rhc,代码行数:26,代码来源:SslTcpClient.cs

示例8: InternalSslSocketHttp

        static byte[] InternalSslSocketHttp(IPEndPoint endpoint, HttpArgs args, HttpMethod method, X509CertificateCollection certificates)
        {
            using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                try
                {
                    client.Connect(endpoint);
                    if (client.Connected)
                    {
                        using (SslStream stream = new SslStream(new NetworkStream(client), false, ValidateServerCertificate, null))
                        {
                            stream.AuthenticateAsClient("ServerName", certificates, SslProtocols.Tls, false);
                            if (stream.IsAuthenticated)
                            {
                                //生成协议包
                                byte[] buff = HttpClient.ParseHttpArgs(method, args);
                                stream.Write(buff, 0, buff.Length);
                                stream.Flush();
                                return ParseSslResponse(endpoint, stream, args, certificates);

                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return null;
        }
开发者ID:abel,项目名称:sinan,代码行数:31,代码来源:SslHttpClient.cs

示例9: SendEmptyPushNotification

        public void SendEmptyPushNotification(string deviceIdentifier, string thumbprint)
        {
            string server = "gateway.push.apple.com";
            using (TcpClient tcpClient = new TcpClient(server, 2195))
            {
                Trace.TraceInformation("Opening SSL Connection...");
                using (SslStream sslStream = new SslStream(tcpClient.GetStream()))
                {
                    try
                    {
                        X509Certificate2Collection certs = new X509Certificate2Collection();

                        Trace.TraceInformation("Adding certificate to connection...");
                        X509Certificate cert = GetAppleServerCert(thumbprint);
                        certs.Add(cert);

                        Trace.TraceInformation("Authenticating against the SSL stream...");
                        sslStream.AuthenticateAsClient(server, certs, SslProtocols.Default, false);
                    }
                    catch (AuthenticationException exp)
                    {
                        Trace.TraceError("Failed to authenticate to APNS - {0}", exp.Message);
                        return;
                    }
                    catch (IOException exp)
                    {
                        Trace.TraceError("Failed to connect to APNS - {0}", exp.Message);
                        return;
                    }

                    byte[] buf = new byte[256];
                    MemoryStream ms = new MemoryStream();
                    BinaryWriter bw = new BinaryWriter(ms);
                    bw.Write(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 });

                    byte[] deviceToken = HexToData(deviceIdentifier);
                    bw.Write(deviceToken);
                    
                    string msg = "{}";

                    bw.Write(new byte[] { 0, 2 });
                    bw.Write(msg.ToCharArray());
                    bw.Flush();

                    Trace.TraceInformation("Message sent. Closing stream...");

                    if (sslStream != null)
                    {
                        sslStream.Write(ms.ToArray());
                    }

                    sslStream.Flush();

                    byte[] response = new byte[6];
                    sslStream.Read(response, 0, 6);
                }
            }
        }
开发者ID:joe-keane,项目名称:dotnet-passbook,代码行数:58,代码来源:SendEmptyPushNotification.cs

示例10: WriteDirectlyToSslStreamTest

        public void WriteDirectlyToSslStreamTest()
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var sslStream = new SslStream(memoryStream,true))
                {
                    sslStream.AuthenticateAsServer(new X509Certificate());
                    byte[] buffer = Encoding.UTF8.GetBytes(_test);
                    sslStream.Write(buffer, 0, buffer.Length);
                    byte[] bytes = Encoding.UTF8.GetBytes(_endMarker);
                    sslStream.Write(bytes, 0, bytes.Length);

                    Assert.AreEqual(_test + _endMarker, Read(sslStream, true));
                    Assert.AreEqual(_test + _endMarker, Read(sslStream, false));
                }

            }
        }
开发者ID:JohanLarsson,项目名称:Next,代码行数:18,代码来源:StreamDummyTests.cs

示例11: Init_ServerCommunication

        public static SslStream Init_ServerCommunication(string URL, int Port)
        {
            UTF8Encoding encoder = new UTF8Encoding();

            //
            //First create the header
            //
            byte ver = 2;
            byte opcode = 0;
            ushort response = 0;
            string uri = @"h";
            string data = "Hiya: \"hi\"";

            byte[] header = new byte[8];
            header[0] = ver;
            header[1] = opcode;
            header[2] = BitConverter.GetBytes(response)[0];
            header[3] = BitConverter.GetBytes(response)[1];

            if (encoder.GetByteCount(uri) > ushort.MaxValue)
                throw new Exception("The URI is too large to send");
            ushort uriLength = (ushort)encoder.GetByteCount(uri);

            if (encoder.GetByteCount(data) > ushort.MaxValue)
                throw new Exception("The data is too large to send");
            ushort dataLength = (ushort)encoder.GetByteCount(data);

            header[4] = BitConverter.GetBytes(uriLength)[0];
            header[5] = BitConverter.GetBytes(uriLength)[1];
            header[6] = BitConverter.GetBytes(dataLength)[0];
            header[7] = BitConverter.GetBytes(dataLength)[1];

            TcpClient clientSocket = new TcpClient(URL, Port);

            SslStream sslStream = new SslStream(clientSocket.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallback));

            sslStream.AuthenticateAsClient(URL);

            sslStream.Write(header, 0, 8);
            sslStream.Write(encoder.GetBytes(uri), 0, uriLength);
            sslStream.Write(encoder.GetBytes(data), 0, dataLength);

            return sslStream;
        }
开发者ID:tcd-tophat,项目名称:networking-test-wp7,代码行数:44,代码来源:Program.cs

示例12: Handle

        public void Handle()
        {
            // Establish an SSL connection
            try
            {
                using (var sslStream = new SslStream(client.GetStream()))
                {

                    sslStream.AuthenticateAsServer(certificate, false, SslProtocols.Default, true);

                    var buffer = new byte[2048];
                    var decoder = Encoding.ASCII.GetDecoder();
                    var chars = new char[buffer.Length];
                    while (true)
                    {
                        // Receive the request
                        var read = sslStream.Read(buffer, 0, buffer.Length);
                        decoder.GetChars(buffer, 0, read, chars, 0);
                        var str = new String(chars);

                        Trace.Write(str.Trim('\0'));

                        // Send the response
                        sslStream.Write(Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("Content-Length: 5\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("Connection: close\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("Hello"));
                    }
                }
            }
            catch(ThreadAbortException tae)
            {
                Trace.TraceInformation("Exiting Handler thread: " + Thread.CurrentThread);
            }
            catch (Exception ex)
            {
            }
        }
开发者ID:vipuldivyanshu92,项目名称:Projects,代码行数:39,代码来源:SslHandler.cs

示例13: RunClient

        public static void RunClient(string machineName, string serverName ="ssl.breakermind.com")
        {
            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient client = new TcpClient("localhost", 8080);
            Console.WriteLine("Client connected.");
            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null
                );
            // The server name must match the name on the server certificate.
            try
            {

                sslStream.AuthenticateAsClient("ssl.breakermind.com");
                DisplaySecurityLevel(sslStream);
                Console.ReadLine();
            }
            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.WriteLine("Server says: {0}", serverMessage);
            // Close the client connection.
            client.Close();
            Console.WriteLine("Client closed.");
        }
开发者ID:fxstar,项目名称:SocketSSL,代码行数:45,代码来源:SSLSocketClient_StartSSLCerts.cs

示例14: RunClient

        public static void RunClient()
        {
            TcpClient client = new TcpClient(serverHost, serverPort);

            SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback (ValidateServerCertificate),
                null
                );

            try
            {
                sslStream.AuthenticateAsClient("none");
            }
            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("GET / HTTP/1.1\r\n\r\n");

            // Send hello message to the server.
            sslStream.Write(messsage);
            sslStream.Flush();

            // Read message from the server.
            string serverMessage = ReadMessage(sslStream);
            Console.WriteLine("Server says: {0}", serverMessage);

            // Close the client connection.
            client.Close();
            Console.WriteLine("Client closed.");
        }
开发者ID:casperbiering,项目名称:VNCTunnel,代码行数:43,代码来源:Main.cs

示例15: Conversation

        public static byte[] Conversation(byte[] request)
        {
            MemoryStream response = new MemoryStream();

            using (TcpClient client = new TcpClient("pkgdsprod.nintendo.co.jp", 12401))
            {
                SslStream sslClient = new SslStream(client.GetStream(), false, delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; });
                sslClient.AuthenticateAsClient("pkgdsprod.nintendo.co.jp");

                sslClient.Write(request, 0, request.Length);
                sslClient.CopyTo(response);
                sslClient.Close();
            }
            response.Flush();
            byte[] dataResponse = response.ToArray();

            int length = BitConverter.ToInt32(dataResponse, 0);
            AssertHelper.Equals(length, dataResponse.Length);

            return dataResponse;
        }
开发者ID:henias,项目名称:pkmn-classic-framework,代码行数:21,代码来源:Program.cs


注:本文中的System.Net.Security.SslStream.Write方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。