Hello.
I'm trying to figure out how WebSocket works using the wss protocol.
Why, when establishing a connection and trying to perform a handshake, it does not happen?
Minimal example.
program Project1;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils,
Classes,
ssockets,
sslsockets,
opensslsockets,
fpopenssl,
base64 { you can add units after this };
const
CRLF = #13#10;
var
Socket: TInetSocket;
SSLHandler: TSSLSocketHandler;
str: ansistring;
SecKey, res: string;
Buf: TBytes;
begin
SSLHandler := TSSLSocketHandler.GetDefaultHandler;
SSLHandler.VerifyPeerCert := False;
Socket := TInetSocket.Create('demo.piesocket.com', 443, SSLHandler);
Socket.Connect;
str := 'GET /v3/channel_1?api_key=VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV¬ify_self HTTP/1.1'
+ CRLF;
str := str + 'Host: demo.piesocket.com' + CRLF;
str := str + 'Connection: Upgrade' + CRLF;
str := str + 'Pragma: no-cache' + CRLF;
str := str + 'Cache-Control: no-cache' + CRLF;
str := str + 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.134 Safari/537.36'
+ CRLF;
str := str + 'Upgrade: websocket' + CRLF;
str := str + 'Origin: https://www.piesocket.com' + CRLF;
str := str + 'Sec-WebSocket-Version: 13' + CRLF;
str := str + 'Accept-Encoding: gzip, deflate, br' + CRLF;
str := str + 'Accept-Language: ru,en;q=0.9' + CRLF;
SecKey := EncodeStringBase64(IntToHex(Random($7FFFFFFFFFFFFFFF), 16));
str := str + 'Sec-WebSocket-Key: ' + SecKey + CRLF;
str := str + 'Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits' + CRLF;
Str := Str + CRLF;
Writeln(Str);
Socket.WriteAnsiString(str);
if Socket.CanRead(5000) then
begin
SetLength(Buf, 1000);
Socket.Read(Buf[0], 1000);
res := TEncoding.UTF8.GetString(Buf);
end;
Writeln('---');
Writeln(res);
Readln;
end.
Log:
GET /v3/channel_1?api_key=VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV¬ify_self HTTP/1.1
Host: demo.piesocket.com
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.134 Safari/537.36
Upgrade: websocket
Origin: https://www.piesocket.com
Sec-WebSocket-Version: 13
Accept-Encoding: gzip, deflate, br
Accept-Language: ru,en;q=0.9
Sec-WebSocket-Key: NkY2NDgyMkVDRDA0NEVCOQ==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
---
HTTP/1.1 400 Bad Request
Server: cloudflare
Date: Sun, 07 Aug 2022 17:04:16 GMT
Content-Type: text/html
Content-Length: 155
Connection: close
CF-RAY: -
<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>cloudflare</center>
</body>
</html>