Skip to content

Instantly share code, notes, and snippets.

@EgorBo
Created May 23, 2017 22:13
Show Gist options
  • Save EgorBo/de50216aff974769d6df1199b6b68608 to your computer and use it in GitHub Desktop.
Save EgorBo/de50216aff974769d6df1199b6b68608 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
namespace SslBug
{
class Program
{
static void Main(string[] args)
{
Test();
Console.ReadKey();
}
static async void Test()
{
string serverAddress = "localhost";
int port = 8080;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.ReceiveTimeout = 10000;
socket.NoDelay = true;
socket.SendBufferSize = 8000;
socket.ReceiveBufferSize = 8000;
socket.Connect(serverAddress, port);
var tcpStream = new NetworkStream(socket, true);
var sslStream = new SslStream(tcpStream, true, (s, cert, chain, policy) => true, null);
sslStream.AuthenticateAsClientAsync(serverAddress).GetAwaiter().GetResult();
SendMessage('c', sslStream);
var msg1 = ReadMessage(sslStream);
Console.WriteLine($"Received SSL message: {msg1.Substring(0, 10)}...");
sslStream.Dispose();
sslStream = null;
socket.Poll(0, SelectMode.SelectError);
SendMessage('c', tcpStream);
var msg2 = ReadMessage(tcpStream);
Console.WriteLine($"Received PLAIN message: {msg2.Substring(0, 10)}...");
Console.WriteLine("Done.");
}
static void SendMessage(char c, Stream stream)
{
var msg = new string(c, 8000) + "<EOF>";
var bytes = Encoding.UTF8.GetBytes(msg);
stream.Write(bytes, 0, bytes.Length);
//stream.Flush();
}
static string ReadMessage(Stream stream)
{
// Read the message sent by the client.
// The client signals the end of the message using the
// "<EOF>" marker.
byte[] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
// Read the client's test message.
bytes = stream.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 or an empty message.
if (messageData.ToString().IndexOf("<EOF>") != -1)
{
break;
}
} while (bytes != 0);
return messageData.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment