3

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\r\n";
socket_listen($socket);

// Accept new connections
$resource = socket_accept($socket);

echo $headers = socket_read($resource, 1024);

preg_match('/Sec-WebSocket-Key\: (.+?)\r\n/', $headers, $key);

$acceptKey = $key[1].'258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
$acceptKey = base64_encode(sha1($acceptKey, true));

$upgrade = "HTTP/1.1 101 Switching Protocols\r\n".
           "Upgrade: websocket\r\n".
           "Connection: Upgrade\r\n".
           "Sec-WebSocket-Accept: $acceptKey".
           "\r\n\r\n";
$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!

MateuszBlaszczyk
  • 133
  • 1
  • 3
  • 10

1 Answers1

1

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.

vtortola
  • 34,709
  • 29
  • 161
  • 263
  • yep. or use a "valid" cert (not self-signed) in the first place. other than that, maybe this gives some hints: http://stackoverflow.com/questions/16979793/php-ratchet-websocket-ssl-connect (if you don't want to reinvent the wheel .. that is WebSocket in PHP) – oberstet May 18 '14 at 06:10
  • My certificate is self signed, but I accepted "the danger" in browser and website normally work with HTTPS yet. My websocket client (in browser) starts under HTTPS. – MateuszBlaszczyk May 18 '14 at 09:46
  • How is the URL you use for connecting? It has to start with WSS:// not HTTPS:// – vtortola May 19 '14 at 09:47