Я пытаюсь создать сервер, который может принимать как безопасное SSL, так и небезопасное текстовое соединение (для обратной совместимости). Мой код почти работает, за исключением того, что первые переданные данные, полученные от небезопасного клиента, теряют первые 5 байтов (символов) на сервере. В частности, если я передаю 30 байтов по незащищенному соединению, когда сервер получает функцию OnClientDataReceived()
, строка «int iRx = nwStream.EndRead(asyn);
», затем iRx = 25
. Любые последующие сообщения, передаваемые от клиента, содержат все отправленные байты/символы, как и ожидалось. Я подозреваю, что первоначальное предположение о том, что соединение является SSLStream
, может заключаться в удалении первых 5 байтов, а затем, когда оно терпит неудачу, эти 5 байтов уже были извлечены из буфера и больше не доступны. Кто-нибудь знает о другом подходе, который я мог бы использовать для написания кода, чтобы сервер мог автоматически переключаться на лету?
Я стараюсь избегать следующих действий:
- Требовать, чтобы клиент подключался с использованием простого текста
NetworkStream
, а затем запрашивал обновление до потока SSL. - Настройка двух
TcpListeners
на двух разных портах (один для безопасного, один для небезопасного)
Вот мой код:
/// Each client that connects gets an instance of the ConnectedClient class.
Class Pseudo_ConnectedClient
{
//Properties
byte[] Buffer; //Holds temporary buffer of read bytes from BeginRead()
TcpClient TCPClient; //Reference to the connected client
Socket ClientSocket; //The outer Socket Reference of the connected client
StringBuilder CurrentMessage; //concatenated chunks of data in buffer until we have a complete message (ends with <ETX>
Stream Stream; //SSLStream or NetworkStream depending on client
ArrayList MessageQueue; //Array of complete messages received from client that need to be processed
}
/// When a new client connects (OnClientConnection callback is executed), the server creates the ConnectedClient object and stores its
/// reference in a local dictionary, then configures the callbacks for incoming data (WaitForClientData)
void OnClientConnection(IAsyncResult result)
{
TcpListener listener = result.AsyncState as TcpListener;
TcpClient clnt = null;
try
{
if (!IsRunning) //then stop was called, so don't call EndAcceptTcpClient because it will throw and ObjectDisposedException
return;
//Start accepting the next connection...
listener.BeginAcceptTcpClient(this.onClientConnection, listener);
//Get reference to client and set flag to indicate connection accepted.
clnt = listener.EndAcceptTcpClient(result);
//Add the reference to our ArrayList of Connected Clients
ConnectedClient conClnt = new ConnectedClient(clnt);
_clientList.Add(conClnt);
//Configure client to listen for incoming data
WaitForClientData(conClnt);
}
catch (Exception ex)
{
Trace.WriteLine("Server:OnClientConnection: Exception - " + ex.ToString());
}
}
/// WaitForClientData registers the AsyncCallback to handle incoming data from a client (OnClientDataReceieved).
/// If a certificate has been provided, then it listens for clients to connect on an SSLStream and configures the
/// BeginAuthenticateAsServer callback. If no certificate is provided, then it only sets up a NetworkStream
/// and prepares for the BeginRead callback.
private void WaitForClientData(ConnectedClient clnt)
{
if (!IsRunning) return; //Then stop was called, so don't do anything
SslStream sslStream = null;
try
{
if (_pfnClientDataCallBack == null) //then define the call back function to invoke when data is received from a connected client
_pfnClientDataCallBack = new AsyncCallback(OnClientDataReceived);
NetworkStream nwStream = clnt.TCPClient.GetStream();
//Check if we can establish a secure connection
if (this.SSLCertificate != null) //Then we have the ability to make an SSL connection (SSLCertificate is a X509Certificate2 object)
{
if (this.certValidationCallback != null)
sslStream = new SslStream(nwStream, true, this.certValidationCallback);
else
sslStream = new SslStream(nwStream, true);
clnt.Stream = sslStream;
//Start Listening for incoming (secure) data
sslStream.BeginAuthenticateAsServer(this.SSLCertificate, false, SslProtocols.Default, false, onAuthenticateAsServer, clnt);
}
else //No certificate available to make a secure connection, so use insecure (unless not allowed)
{
if (this.RequireSecureConnection == false) //Then we can try to read from the insecure stream
{
clnt.Stream = nwStream;
//Start Listening for incoming (unsecure) data
nwStream.BeginRead(clnt.Buffer, 0, clnt.Buffer.Length, _pfnClientDataCallBack, clnt);
}
else //we can't do anything - report config problem
{
throw new InvalidOperationException("A PFX certificate is not loaded and the server is configured to require a secure connection");
}
}
}
catch (Exception ex)
{
DisconnectClient(clnt);
}
}
/// OnAuthenticateAsServer first checks if the stream is authenticated, if it isn't it gets the TCPClient's reference
/// to the outer NetworkStream (client.TCPClient.GetStream()) - the insecure stream and calls the BeginRead on that.
/// If the stream is authenticated, then it keeps the reference to the SSLStream and calls BeginRead on it.
private void OnAuthenticateAsServer(IAsyncResult result)
{
ConnectedClient clnt = null;
SslStream sslStream = null;
if (this.IsRunning == false) return;
try
{
clnt = result.AsyncState as ConnectedClient;
sslStream = clnt.Stream as SslStream;
if (sslStream.IsAuthenticated)
sslStream.EndAuthenticateAsServer(result);
else //Try and switch to an insecure connections
{
if (this.RequireSecureConnection == false) //Then we are allowed to accept insecure connections
{
if (clnt.TCPClient.Connected)
clnt.Stream = clnt.TCPClient.GetStream();
}
else //Insecure connections are not allowed, close the connection
{
DisconnectClient(clnt);
}
}
}
catch (Exception ex)
{
DisconnectClient(clnt);
}
if( clnt.Stream != null) //Then we have a stream to read, start Async read
clnt.Stream.BeginRead(clnt.Buffer, 0, clnt.Buffer.Length, _pfnClientDataCallBack, clnt);
}
/// OnClientDataReceived callback is triggered by the BeginRead async when data is available from a client.
/// It determines if the stream (as assigned by OnAuthenticateAsServer) is an SSLStream or a NetworkStream
/// and then reads the data out of the stream accordingly. The logic to parse and process the message has
/// been removed because it isn't relevant to the question.
private void OnClientDataReceived(IAsyncResult asyn)
{
try
{
ConnectedClient connectClnt = asyn.AsyncState as ConnectedClient;
if (!connectClnt.TCPClient.Connected) //Then the client is no longer connected >> clean up
{
DisconnectClient(connectClnt);
return;
}
Stream nwStream = null;
if( connectClnt.Stream is SslStream) //Then this client is connected via a secure stream
nwStream = connectClnt.Stream as SslStream;
else //this is a plain text stream
nwStream = connectClnt.Stream as NetworkStream;
// Complete the BeginReceive() asynchronous call by EndReceive() method which
// will return the number of characters written to the stream by the client
int iRx = nwStream.EndRead(asyn); //Returns the numbers of bytes in the read buffer
char[] chars = new char[iRx];
// Extract the characters as a buffer and create a String
Decoder d = ASCIIEncoding.UTF8.GetDecoder();
d.GetChars(connectClnt.Buffer, 0, iRx, chars, 0);
//string data = ASCIIEncoding.ASCII.GetString(buff, 0, buff.Length);
string data = new string(chars);
if (iRx > 0) //Then there was data in the buffer
{
//Append the current packet with any additional data that was already received
connectClnt.CurrentMessage.Append(data);
//Do work here to check for a complete message
//Make sure two complete messages didn't get concatenated in one transmission (mobile devices)
//Add each message to the client's messageQueue
//Clear the currentMessage
//Any partial messsage at the end of the buffer needs to be added to the currentMessage
//Start reading again
nwStream.BeginRead(connectClnt.Buffer, 0, connectClnt.Buffer.Length, OnClientDataReceived, connectClnt);
}
else //zero-length packet received - Disconnecting socket
{
DisconnectClient(connectClnt);
}
}
catch (Exception ex)
{
return;
}
}
Что работает:
- Если у сервера нет сертификата, используется только NetworkStream, и все байты принимаются от клиента для всех сообщений.
- Если у сервера есть сертификат (настроен SSLStream) и может быть установлено безопасное соединение (веб-браузер с использованием https://), и для всех сообщений будет получено полное сообщение.
Что не работает:
- Если у сервера есть сертификат (настроен
SSLStream
) и от клиента установлено небезопасное соединение, при получении первого сообщения от этого клиента код правильно определяет, чтоSSLStream
не прошел проверку подлинности, и переключается наNetworkStream
изTCPClient
. Однако, когдаEndRead
вызывается для этогоNetworkStream
для первого сообщения, первые 5 символов (байтов) отсутствуют в отправленном сообщении, но только для первого сообщения. Все остальные сообщения завершены, покаTCPClient
подключен. Если клиент отключается, а затем снова подключается, первое сообщение обрезается, после чего все последующие сообщения снова являются правильными.
Что вызывает обрезание этих первых 5 байтов и как этого избежать?
Мой проект в настоящее время использует .NET v3.5... Я хотел бы остаться на этой версии и не переходить на 4.0, если я могу этого избежать.
Дополнительный вопрос
Ответ Дэмиена ниже позволяет мне сохранить эти недостающие 5 байтов, однако я бы предпочел придерживаться методов BeginRead
и EndRead
в своем коде, чтобы избежать блокировки. Есть ли хорошие учебные пособия, показывающие «лучшие методы» при их переопределении? Точнее, как работать с объектом IAsyncResult
. Я понимаю, что мне нужно будет добавить любой контент, который хранится в буферах RestartableStream, а затем перейти во внутренний поток (базу), чтобы получить остальное и вернуть торал. Но поскольку объект IAsyncResult
является пользовательским классом, я не могу понять общий способ, которым я могу комбинировать баффы RestartableStream с баффами внутреннего потока перед возвратом. Нужно ли мне также реализовывать BeginRead(), чтобы я знал, в каких буферах пользователь хочет хранить содержимое? Я предполагаю, что другое решение, поскольку проблема с отброшенными байтами связана только с первым сообщением от клиента (после этого я знаю, использовать ли его как SSLStream
или NetworkStream
), будет заключаться в том, чтобы обработать это первое сообщение, напрямую вызвав Read()
метод RestartableStream (временно блокируя код), затем для всех будущих сообщений используйте асинхронные обратные вызовы для чтения содержимого, как я делаю сейчас.