Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /* < < < < < < < < -< MODULES >- > > > > > > > > */
- require_once("classes/chat.php");
- $chat = new Chat();
- $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
- /* < < < < < < < < -< VARIABLES >- > > > > > > > */
- $url = 'localhost/chat';
- $port = 8091;
- $ip = 0;
- /* < < < < < < < < -< CONNECTED >- > > > > > > > */
- socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
- socket_bind($socket, $ip, $port);
- socket_listen($socket);
- $clientSocketArray = array($socket);
- $null = null;
- while(true) {
- $newSocketArray = $clientSocketArray;
- socket_select($newSocketArray, $null, $null, 0, 10);
- if(in_array($socket, $newSocketArray)) {
- $newSocket = socket_accept($socket);
- $clientSocketArray[] = $newSocket;
- $header = socket_read($newSocket, 1024);
- $chat -> sendHeaders($header, $newSocket, $url, $port);
- socket_getpeername($newSocket, $client_ip_address);
- $connectionACK = $chat -> newConnectionACK($client_ip_address);
- $chat -> send($connectionACK, $clientSocketArray);
- }
- }
- /* < < < < < < < -< CLOSE-CONNECT >- > > > > > > */
- socket_close($socket);
- ?>
- <?php
- class Chat {
- /*<-->*/
- public function sendHeaders($headersText, $newSocket, $host, $port) {
- $headers = array();
- $tmpLine = preg_split("/rn/", $headersText);
- foreach($tmpLine as $line) {
- $line = rtrim($line);
- if(preg_match('/A(S+): (.*)z/', $line, $matches)) {
- $headers[$matches[1]] = $matches[2];
- }
- }
- $key = $headers['Sec-WebSocket-Key'];
- $sKey = base64_encode(pack('H*', sha1($key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
- $strHeadr = "HTTP/1.1 101 Switching Protocolsrn" .
- "Upgrade: websocketrn" .
- "Connection: Upgradern" .
- "WebSocket-Origin: $hostrn" .
- "WebSocket-Location: ws://$host:$port/chat/server.phprn" .
- "Sec-WebSocket-Accept: $sKeyrnrn"
- ;
- socket_write($newSocket, $strHeadr, strlen($strHeadr));
- }
- /*<-->*/
- public function newConnectionACK($client_ip_address) {
- $message = "New client $client_ip_address connected";
- $messageArray = [
- "text" => $message,
- "type" => "newConnectionACK"
- ];
- $ack = $this->seal(json_encode($messageArray));
- return $ack;
- }
- /*<-->*/
- public function seal($socketData) {
- $b1 = 0x81;
- $lenght = strlen($socketData);
- $text = "";
- if($lenght <= 125) {
- $text = pack('CC', $b1, $lenght);
- } else if($lenght > 125 && $lenght < 65536) {
- $text = pack('CCn', $b1, 126, $lenght);
- } else if($lenght > 65535) {
- $text = pack('CCNN', $b1, 127, $lenght);
- }
- return $text.$socketData;
- }
- /*<-->*/
- public function send($message, $clientSocketArray) {
- $messageLenght = strlen($message);
- foreach($clientSocketArray as $clientSocket) {
- socket_write($clientSocket, $message, $messageLenght);
- }
- var_export( $clientSocketArray );
- return true;
- }
- /*<-->*/
- }
Add Comment
Please, Sign In to add comment