本文整理汇总了C#中System.Net.Security.SslStream.Read方法的典型用法代码示例。如果您正苦于以下问题:C# SslStream.Read方法的具体用法?C# SslStream.Read怎么用?C# SslStream.Read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Security.SslStream
的用法示例。
在下文中一共展示了SslStream.Read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Test
static void Test()
{
// Connect as client to port 1300
string server = "127.0.0.1";
TcpClient client = new TcpClient(server, 1300);
// Create a secure stream
using (SslStream sslStream = new SslStream(client.GetStream(), false,
new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
{
sslStream.AuthenticateAsClient(server);
// ... Send and read data over the stream
byte[] buffer = new byte[1024];
int n = sslStream.Read(buffer, 0, 1024);
string _message = System.Text.Encoding.UTF8.GetString(buffer, 0, n);
System.Console.WriteLine("Client said: " + _message);
}
// Disconnect and close the client
client.Close();
}
示例2: 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);
}
}
示例3: 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))
//.........这里部分代码省略.........
示例4: 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);
}
}
}
示例5: ReadMessage
public static string ReadMessage(SslStream sslStream, TcpClient client)
{
byte[] buffer = new byte[256];
int totalRead = 0;
//read bytes until stream indicates there are no more
do
{
int read = sslStream.Read(buffer, totalRead, buffer.Length - totalRead);
totalRead += read;
Console.WriteLine("ReadMessage: " + read);
} while (client.GetStream().DataAvailable);
return Encoding.Unicode.GetString(buffer, 0, totalRead);
}
示例6: ReadMessage
static string ReadMessage(SslStream sslStream)
{
byte[] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
bytes = sslStream.Read(buffer, 0, buffer.Length);
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
decoder.GetChars(buffer, 0, bytes, chars, 0);
messageData.Append(chars);
if (messageData.ToString().Contains(@"</Document>") == true)
{
break;
}
} while (bytes != 0);
return messageData.ToString();
}
示例7: 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)
{
}
}
示例8: ReadFromSslStream
private static byte[] ReadFromSslStream(SslStream stream, int max)
{
byte[] buffer = new byte[max];
byte[] retval;
if (stream.CanRead)
{
int bytesread = stream.Read(buffer, 0, max);
retval = new byte[bytesread];
using (MemoryStream ms = new MemoryStream(buffer))
{
ms.Read(retval, 0, bytesread);
}
return retval;
}
else
{
retval = new byte[0];
return retval;
}
}
示例9: readMessage
private string readMessage(SslStream stream)
{
byte[] buffer = new byte[2048];
StringBuilder input = new StringBuilder();
int bytes = -1;
do
{
bytes = stream.Read(buffer, 0, buffer.Length);
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
decoder.GetChars(buffer, 0, bytes, chars, 0);
input.Append(chars);
if (input.ToString().IndexOf("<EOF>") != -1)
{
break;
}
}
while (bytes != 0);
return input.ToString();
}
示例10: HandleClient
public override void HandleClient(object obj)
{
TcpClient client = (TcpClient)obj;
byte[] message = new byte[10000];
X509Certificate2 certificate = new X509Certificate2(Certificate.blazeServer, "123456");
SslStream stream = new SslStream(client.GetStream(), false);
try
{
stream.AuthenticateAsServer(certificate, false, SslProtocols.Ssl3, false);
}
catch
{
client.Close();
}
Log.Info("Client connected to Blaze.");
// increase number of connections
_connections += 1;
// add the client to dictionary
ClientManager.AddClient(_connections, client.Client.RemoteEndPoint, stream);
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
bytesRead = stream.Read(message, 0, message.Length);
}
catch
{
Log.Info("Client disconnected from Blaze.");
client.Close();
var clientId = _connections;
var cl = ClientManager.GetClient(clientId);
Log.Info(string.Format("Deleting client {0} (disconnected).", clientId));
if (cl.type == ClientType.CLIENT_TYPE_DEDICATED_SERVER && cl.gameId != 0)
{
Log.Info("Deleting game from disconnected event");
Database.DeleteGame(cl.gameId);
}
ClientManager.clients.Remove(clientId);
break;
}
if (bytesRead == 0)
{
break;
}
else
{
// decode the packet
FireFrame fireFrame = new FireFrame(message);
Packet packet = fireFrame.Decode();
Router.HandleRequest(_connections, packet, stream);
}
}
client.Close();
}
示例11: SocketStream
public virtual string SocketStream(string xmlRequestFilePath, string xmlResponseDestinationDirectory, Dictionary<string, string> config)
{
var url = config["onlineBatchUrl"];
var port = int.Parse(config["onlineBatchPort"]);
TcpClient tcpClient;
SslStream sslStream;
try
{
tcpClient = new TcpClient(url, port);
sslStream = new SslStream(tcpClient.GetStream(), false, ValidateServerCertificate, null);
}
catch (SocketException e)
{
throw new LitleOnlineException("Error establishing a network connection", e);
}
try
{
sslStream.AuthenticateAsClient(url);
}
catch (AuthenticationException e)
{
tcpClient.Close();
throw new LitleOnlineException("Error establishing a network connection - SSL Authencation failed", e);
}
if ("true".Equals(config["printxml"]))
{
Console.WriteLine("Using XML File: " + xmlRequestFilePath);
}
using (var readFileStream = new FileStream(xmlRequestFilePath, FileMode.Open))
{
int bytesRead;
do
{
var byteBuffer = new byte[1024 * sizeof(char)];
bytesRead = readFileStream.Read(byteBuffer, 0, byteBuffer.Length);
sslStream.Write(byteBuffer, 0, bytesRead);
sslStream.Flush();
} while (bytesRead != 0);
}
var batchName = Path.GetFileName(xmlRequestFilePath);
var destinationDirectory = Path.GetDirectoryName(xmlResponseDestinationDirectory);
if (destinationDirectory != null && !Directory.Exists(destinationDirectory)) Directory.CreateDirectory(destinationDirectory);
if ("true".Equals(config["printxml"]))
{
Console.WriteLine("Writing to XML File: " + xmlResponseDestinationDirectory + batchName);
}
using (var writeFileStream = new FileStream(xmlResponseDestinationDirectory + batchName, FileMode.Create))
{
int bytesRead;
do
{
var byteBuffer = new byte[1024 * sizeof(char)];
bytesRead = sslStream.Read(byteBuffer, 0, byteBuffer.Length);
writeFileStream.Write(byteBuffer, 0, bytesRead);
} while (bytesRead > 0);
}
tcpClient.Close();
sslStream.Close();
return xmlResponseDestinationDirectory + batchName;
}
示例12: ParseSslResponse
/// <summary>
/// 解析 Ssl Response
/// </summary>
/// <param name="endpoint"></param>
/// <param name="ssl"></param>
/// <param name="args"></param>
/// <param name="certificates"></param>
/// <returns></returns>
private static byte[] ParseSslResponse(IPEndPoint endpoint,
SslStream ssl,
HttpArgs args,
X509CertificateCollection certificates)
{
//尝试10秒时间读取协议头
CancellationTokenSource source = new CancellationTokenSource();
Task<string> myTask = Task.Factory.StartNew<string>(
new Func<object, string>(ReadSslHeaderProcess),
ssl,
source.Token);
if (myTask.Wait(10000))
{
string header = myTask.Result;
if (header.StartsWith("HTTP/1.1 302"))
{
int start = header
.ToUpper().IndexOf("LOCATION");
if (start > 0)
{
string temp = header.Substring(start, header.Length - start);
string[] sArry = Regex.Split(temp, "\r\n");
args.Url = sArry[0].Remove(0, 10);
return Get(endpoint, args, certificates); //注意:302协议需要重定向
}
}
else if (header.StartsWith("HTTP/1.1 200")) //继续读取内容
{
int start = header
.ToUpper().IndexOf("CONTENT-LENGTH");
int content_length = 0;
if (start > 0)
{
string temp = header.Substring(start, header.Length - start);
string[] sArry = Regex.Split(temp, "\r\n");
content_length = Convert.ToInt32(sArry[0].Split(':')[1]);
if (content_length > 0)
{
byte[] bytes = new byte[content_length];
if (ssl.Read(bytes, 0, bytes.Length) > 0)
{
return bytes;
}
}
}
else
{
//不存在Content-Length协议头
return ParseSslResponse(ssl);
}
}
else
{
return Encoding.Default.GetBytes(header);
}
}
else
{
source.Cancel(); //超时的话,别忘记取消任务哦
}
return null;
}
示例13: ReadMessage
static string ReadMessage(SslStream sslStream)
{
// Read the message sent by the server.
// The end of the message is signaled using the
// "<EOF>" marker.
byte [] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
bytes = sslStream.Read(buffer, 0, buffer.Length);
// Use Decoder class to convert from bytes to UTF8
// in case a character spans two buffers.
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
decoder.GetChars(buffer, 0, bytes, chars,0);
messageData.Append (chars);
// Check for EOF.
if (messageData.ToString().IndexOf("<EOF>") != -1)
{
break;
}
} while (bytes != 0);
return messageData.ToString();
}
示例14: QuickRead
private static string QuickRead(SslStream sslStream)
{
_readBuffer = new byte[ConfigurationSupport.bufferSize];
int offset = 0;
int count = 0;
StringBuilder builder = new StringBuilder();
if (sslStream != null)
{
do
{
count = sslStream.Read(_readBuffer, 0, _readBuffer.Length);
System.Text.Decoder decoder = Encoding.ASCII.GetDecoder();
char[] chars = new char[decoder.GetCharCount(_readBuffer, 0, count)];
decoder.GetChars(_readBuffer, 0, count, chars, 0);
builder.Append(chars);
if (builder.ToString().IndexOf("\n") != -1)
{
break;
}
}
while (count != 0);
}
else
{
do
{
int num3 = _client.GetStream().Read(_readBuffer, offset, _readBuffer.Length - offset);
offset += num3;
}
while (_client.GetStream().DataAvailable);
builder.Append(Encoding.ASCII.GetString(_readBuffer, 0, offset));
}
return builder.ToString().TrimEnd(new char[] { '\r', '\n' });
}
示例15: ServiceClient
public void ServiceClient(object remote)
{
TcpClient client = (TcpClient)remote;
try
{
String input = "";
Byte[] data = new Byte[8192];
Byte[] send = null;
String[] returnValue = null;
Int32 bytesRec = 0;
Int32 marker = -1;
Boolean escape = false;
Boolean tls = false;
send = Encoding.UTF8.GetBytes(String.Format("# munin node at {0}\n", System.Environment.MachineName));
NetworkStream stream = client.GetStream();
stream.Write(send, 0, send.Length);
while (!escape && !tls && ((bytesRec = stream.Read(data, 0, 8192)) > 0))
{
input += Encoding.UTF8.GetString(data, 0, bytesRec);
NodeService.log("Input: " + input);
while (!escape && ((marker = input.IndexOfAny(lineBreaks)) > -1))
{
String command = input.Substring(0, marker);
input = input.Substring(marker + 1);
NodeService.log("Received: " + command);
if (processDelegate != null)
{
returnValue = processDelegate(command);
if (returnValue != null)
{
foreach (String s in returnValue)
{
NodeService.log(String.Format("Sending ({0}): {1}", s.Length, s));
stream.Write(Encoding.UTF8.GetBytes(s), 0, s.Length);
tls = s.Equals("TLS OK\n");
}
}
else
{
escape = true;
}
}
}
}
if (tls)
{
SslStream sslStream = new SslStream(stream, false);
NodeService.log("SSL stream opened");
try
{
try
{
sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, false);
}
catch (Exception ex)
{
NodeService.log(ex.Message);
}
while (!escape && ((bytesRec = sslStream.Read(data, 0, 8192)) > 0))
{
input += Encoding.UTF8.GetString(data, 0, bytesRec);
NodeService.log("TLS Input: " + input);
while (!escape && ((marker = input.IndexOfAny(lineBreaks)) > -1))
{
string command = input.Substring(0, marker);
input = input.Substring(marker + 1);
NodeService.log("TLS Received: " + command);
if (processDelegate != null)
{
returnValue = processDelegate(command);
if (returnValue != null)
{
foreach (String s in returnValue)
{
NodeService.log(String.Format("TLS Sending ({0}): {1}", s.Length, s));
sslStream.Write(Encoding.UTF8.GetBytes(s));
}
}
else
{
escape = true;
}
}
}
}
}
catch (AuthenticationException e)
{
NodeService.log(String.Format("Exception: {0}", e.Message));
if (e.InnerException != null)
{
NodeService.log(String.Format("Inner exception: {0}", e.InnerException.Message));
}
}
finally
{
//.........这里部分代码省略.........