本文整理汇总了C#中System.Net.Security.SslStream.Flush方法的典型用法代码示例。如果您正苦于以下问题:C# SslStream.Flush方法的具体用法?C# SslStream.Flush怎么用?C# SslStream.Flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Security.SslStream
的用法示例。
在下文中一共展示了SslStream.Flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ProcessTcpClient
static void ProcessTcpClient(TcpClient client)
{
try
{
SslStream stream = new SslStream(client.GetStream());
X509Certificate cert = new X509Certificate2(Certificate.CreateSelfSignCertificatePfx(
"CN=localhost", //host name
DateTime.Parse("2000-01-01"), //not valid before
DateTime.Parse("2099-01-01"), //not valid after
"mypassword"), "mypassword"); //password to encrypt key file)
stream.AuthenticateAsServer(cert);
byte[] requestBuffer = new byte[8192];
int read = stream.Read(requestBuffer, 0, 8192);
Array.Resize<byte>(ref requestBuffer, read);
string request = Encoding.UTF8.GetString(requestBuffer);
string requestedPath = request.Split('?')[0].Replace("GET ", "");
Console.WriteLine(client.GetHashCode() + " => " + requestedPath);
string response = "";
if (requestedPath == "/gamepad/shardlist")
{
}
else if (requestedPath == "/gamepad/lastshard")
{
}
string header = "HTTP/1.1 200 OK\r\nDate: Fri, 10 Feb 2012 09:19:00 GMT\r\nServer: Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o\r\nContent-Length: " + response.Length + "\r\nContent-Type: text/html\r\n\r\n";
byte[] headerBytes = Encoding.UTF8.GetBytes(header);
byte[] responseBytes = Encoding.UTF8.GetBytes(response);
stream.Write(headerBytes);
stream.Flush();
stream.Write(responseBytes);
stream.Flush();
}
catch (Exception e)
{
Console.WriteLine("Exception occured!\nMessage: " + e.Message + "\n" + e.StackTrace);
}
}
示例2: 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);
}
}
示例3: 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;
}
示例4: 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;
}
示例5: 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();
}
示例6: 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);
}
}
示例7: 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);
}
}
}
示例8: Main
static void Main (string [] args)
{
certfile = (args.Length > 1) ? args [0] : "ssl.cer";
keyfile = (args.Length > 1) ? args [1] : "ssl.pvk";
Socket listenSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint (IPAddress.Any, 4433);
Socket requestSocket;
listenSocket.Bind (localEndPoint);
listenSocket.Listen (10);
while (true) {
try {
requestSocket = listenSocket.Accept ();
using (NetworkStream ns = new NetworkStream (requestSocket, FileAccess.ReadWrite, true)) {
using (SslStream s = new SslStream (ns, false, new RemoteCertificateValidationCallback (VerifyClientCertificate))) {
s.AuthenticateAsServer (Certificate, false, SslProtocols.Default, false);
StreamReader reader = new StreamReader (s);
StreamWriter writer = new StreamWriter (s, Encoding.ASCII);
string line;
// Read request header
do {
line = reader.ReadLine ();
if (line != null)
Console.WriteLine (line);
}
while (line != null && line.Length > 0);
string answer = String.Format ("HTTP/1.0 200{0}Connection: close{0}" +
"Content-Type: text/html{0}Content-Encoding: {1}{0}{0}" +
"<html><body><h1>Hello {2}!</h1></body></html>{0}",
"\r\n", Encoding.ASCII.WebName,
s.RemoteCertificate == null ? "World" : s.RemoteCertificate.GetName ());
// Send response
writer.Write (answer);
writer.Flush ();
s.Flush ();
ns.Flush ();
}
}
}
catch (Exception ex) {
Console.WriteLine ("---------------------------------------------------------");
Console.WriteLine (ex.ToString ());
}
}
}
示例9: SendPacket
/// <summary>
/// Send a packet.</summary>
/// <param name="packet">The packet that will be send</param>
/// <param name="ssl">The ssl stream</param>
public static bool SendPacket(Packet packet, SslStream ssl)
{
BinaryFormatter binairyFormatter = new BinaryFormatter();
try
{
binairyFormatter.Serialize(ssl, packet);
ssl.Flush();
}
catch (Exception)
{
return false;
}
return true;
}
示例10: ReadPacket
/// <summary>
/// Receive and read a packet.</summary>
/// <param name="ssl">The ssl stream</param>
public static Packet ReadPacket(SslStream ssl)
{
BinaryFormatter binairyFormatter = new BinaryFormatter();
Packet packet;
try
{
packet = (Packet)binairyFormatter.Deserialize(ssl);
ssl.Flush();
}
catch (Exception)
{
return null;
}
return packet;
}
示例11: 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.");
}
示例12: 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.");
}
示例13: RunClient
public static void RunClient(string machineName, string serverName, int port)
{
TcpClient client = new TcpClient(machineName, port);
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(serverName);
}
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;
}
byte[] message = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
// Send hello message to the server.
sslStream.Write(message);
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.");
}
示例14: Send
public static void Send(string s, SslStream sslStream)
{
byte[] b = Encoding.ASCII.GetBytes(s);
sslStream.Write(b, 0, b.Length);
sslStream.Flush();
}
示例15: Connect
public void Connect()
{
string host = mUrl.DnsSafeHost;
string path = mUrl.PathAndQuery;
string origin = "http://" + host;
mSslStream = CreateSocket(mUrl);
StringBuilder extraHeaders = new StringBuilder();
if (mHeaders != null)
{
foreach (KeyValuePair<string, string> header in mHeaders)
extraHeaders.Append(header.Key + ": " + header.Value + "\r\n");
}
string request = "GET " + path + " HTTP/1.1\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
"Host: " + host + "\r\n" +
"Sec-WebSocket-Version: 6\r\n" +
"Sec-WebSocket-Origin: https://" + host + "\r\n" +
"Sec-WebSocket-Extensions: deflate-stream\r\n" +
"Sec-WebSocket-Key: HSmrc0sMlYUkAGmm5OPpG2HaGWk=\r\n" + // note see: https://en.wikipedia.org/wiki/WebSocket on draft-ietf-hybi-thewebsocketprotocol-06 version of protocol for instructions on how to construct the key
extraHeaders.ToString() + "\r\n";
byte[] sendBuffer = Encoding.UTF8.GetBytes(request);
mSslStream.Write(sendBuffer, 0, sendBuffer.Length);
mSslStream.Flush();
string reply = ReadMessage(mSslStream);
if (!reply.Equals("HTTP/1.1 101 Web Socket Protocol Handshake"))
throw new IOException("Invalid handshake response");
if (!reply.Equals("Upgrade: WebSocket"))
throw new IOException("Invalid handshake response");
if (!reply.Equals("Connection: Upgrade"))
throw new IOException("Invalid handshake response");
mHandshakeComplete = true;
}