I'm starting with websockets and I learned how to do handshake. This code does handshake without SSL, I added SSL cert to my server and it doesn't work now:
$host = '176.xxx.xx.xx';
$port = 44444;
//Create TCP/IP sream socket and return the socket resource
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// Bind the source address
socket_bind($socket, $host, $port);
// Listen to incoming connection
echo "listening
";
socket_listen($socket);
// Accept new connections
$resource = socket_accept($socket);
echo $headers = socket_read($resource, 1024);
preg_match('/Sec-WebSocket-Key\: (.+?)
/', $headers, $key);
$acceptKey = $key[1].'258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
$acceptKey = base64_encode(sha1($acceptKey, true));
$upgrade = "HTTP/1.1 101 Switching Protocols
".
"Upgrade: websocket
".
"Connection: Upgrade
".
"Sec-WebSocket-Accept: $acceptKey".
"
";
$r1 = socket_write($resource,$upgrade,strlen($upgrade));
socket_close($resource);
I know it is not perfect code - I can improve it yourself, but I can't solve SSL problem yourself. So please focus on that.
I was searching a lot, but I found only very complicated solution and I can't use them at all. I have to use .pem file with my cert and private key, but how should I add it to that socket? Please don't give me solution with node.js or socket.io, it has to be made with PHP. Moreover, I prefer to not use any complicated classes, because I want to know bases and create my own class - the reason is that I want to use websockets for very specififc problem.
Thank you a lot!
If you are using a self signed certificate, ensure you serve the page using HTTPS as well, so you can accept the warning that the browser will show because the lack of valid CA in the certificate. Otherwise, if you serve the page under HTTP, and use a WSS websocket with a self signed certificate, the connection will fail.