Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Websocket test</title>
  6. </head>
  7. <body>
  8. <form action="">
  9. <div style="border: 1px solid grey; padding: 10px;">No result</div>
  10. </form>
  11. <script>
  12. let socket = new WebSocket('ws://websocket.loc:8080/server.php');
  13. socket.onopen = function() {
  14. console.log('Connected');
  15. };
  16. socket.onerror = function(error) {
  17. console.log('Error: "'+error.message+'"');
  18. };
  19. socket.onclose = function() {
  20. console.log('Closed');
  21. };
  22. socket.onmessage = function(event) {
  23. let data = JSON.parse(event.data);
  24. console.log('Type: '+data.type+'; message: '+data.message);
  25. };
  26. </script>
  27. </body>
  28. </html>
  29.  
  30. <?php
  31.  
  32. function sendHeaders($headersText, $newSocket, $host, $port) {
  33. $headers = [];
  34. $tmpLine = preg_split("/rn/", $headersText);
  35. foreach ($tmpLine as $line) {
  36. $line = rtrim($line);
  37. if (preg_match("/A(S+): (.*)z/", $line, $matches)) {
  38. $headers[$matches[1]] = $matches[2];
  39. }
  40. }
  41. $key = $headers['Sec-WebSocket-Key'];
  42. $sKey = base64_encode(pack('H*', sha1($key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
  43. $strHeadr = "
  44. HTTP/1.1 101 Switching Protocols rn
  45. Upgrade: websocketrn
  46. Connection: Upgradern
  47. WebSocket-Origin: $hostrn
  48. WebSocket-Location: ws://$host:$port/server.phprn
  49. Sec-WebSocket-Accept:$sKeyrnrn
  50. ";
  51. socket_write($newSocket, $strHeadr, strlen($strHeadr));
  52. }
  53.  
  54. define('PORT', '8080');
  55.  
  56. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  57.  
  58. socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
  59. socket_bind($socket, 0, PORT);
  60.  
  61. socket_listen($socket);
  62.  
  63. while (true) {
  64. $newSocket = socket_accept($socket);
  65. $header = socket_read($newSocket, 1024);
  66. sendHeaders($header, $newSocket, $_SERVER['HTTP_HOST'], PORT);
  67. }
  68.  
  69. socket_close($socket);
  70.  
  71. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement