Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add property OnConnected, SecWebKey, Header #5

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions WebSocketServer.pas
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@ interface
IdSSL, IdSSLOpenSSL;

type
TWebSocketServerConnectedEvent = procedure(AContext: TIdContext) of object;

TWebSocketServer = class(TIdCustomTCPServer)
private
IdServerIOHandlerSSLOpenSSL: TIdServerIOHandlerSSLOpenSSL;
HashSHA1: TIdHashSHA1;
FHeaders: TDictionary<string, string>;
FSecWebSocketKey: string;
FOnConnected: TWebSocketServerConnectedEvent;

protected
procedure DoConnect(AContext: TIdContext); override;
Expand All @@ -26,6 +30,10 @@ TWebSocketServer = class(TIdCustomTCPServer)

constructor Create;
destructor Destroy; override;

property Headers: TDictionary<string, string> read FHeaders;
property SecWebSocketKey: string read FSecWebSocketKey;
property OnConnected: TWebSocketServerConnectedEvent read FOnConnected write FOnConnected;
end;

TWebSocketIOHandlerHelper = class(TIdIOHandler)
Expand Down Expand Up @@ -102,8 +110,8 @@ function TWebSocketServer.DoExecute(AContext: TIdContext): Boolean;
var
c: TIdIOHandler;
Bytes: TArray<byte>;
msg, SecWebSocketKey, Hash: string;
ParsedHeaders: TDictionary<string, string>;
msg, Hash: string;
// ParsedHeaders: TDictionary<string, string>;
begin
c := AContext.Connection.IOHandler;

Expand All @@ -122,15 +130,15 @@ function TWebSocketServer.DoExecute(AContext: TIdContext): Boolean;
except
end;

ParsedHeaders := HeadersParse(msg);
FHeaders := HeadersParse(msg);

if ParsedHeaders.ContainsKey('Upgrade') and (ParsedHeaders['Upgrade'] = 'websocket') and
ParsedHeaders.ContainsKey('Sec-WebSocket-Key') then
if FHeaders.ContainsKey('Upgrade') and (FHeaders['Upgrade'] = 'websocket') and
FHeaders.ContainsKey('Sec-WebSocket-Key') then
begin
// Handle handshake request
// https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers

SecWebSocketKey := ParsedHeaders['Sec-WebSocket-Key'];
FSecWebSocketKey := FHeaders['Sec-WebSocket-Key'];

// Send handshake response
Hash := TIdEncoderMIME.EncodeBytes(
Expand All @@ -149,7 +157,9 @@ function TWebSocketServer.DoExecute(AContext: TIdContext): Boolean;
c.Tag := 1;
end;

ParsedHeaders.DisposeOf;
Headers.DisposeOf;
if Assigned(FOnConnected) then
FOnConnected(AContext);
end;
end;

Expand Down