📜 ⬆️ ⬇️

Text chat for the site

image

I want to share the experience of creating a text chat based on the nginx-push-stream-module of the Nginx, PHP and Javascript module. This module functions on the principle of long polling and can be used both for instant messaging between users and for the system of push notifications.

Adding Nginx module


We assume that you have already installed Nginx. Therefore, first you need to download and add the nginx-push-stream-module module and rebuild Nginx manually. A detailed guide to adding a module can be found here and here , I think it makes no sense to write again.

Configuration


To support long polling, in the Nginx configuration, we will declare a message publishing point (in this example, publish) and a subscription point for receiving messages (in this example, subscribe).
')
http { … server { … location /publish { push_stream_publisher admin; #      push_stream_channels_path $arg_id; # id     push_stream_store_messages on; #      allow 127.0.0.1; #         } location ~ /subscribe/(.*) { push_stream_subscriber long-polling ; #     # (  ) push_stream_channels_path $1; # id    push_stream_longpolling_connection_ttl 300s; #  ,     #   ( )  #  push_stream_last_received_message_time $arg_time; #     push_stream_last_received_message_tag $arg_tag; # ,    # } } push_stream_shared_memory_size 32M; } 


Inside the http block, you need to specify the directive push_stream_shared_memory_size, that is, the size of the allocated memory.

Posting to PHP


In PHP, messages are sent using the usual POST method.

 $channel_id = subscriber1; //id     $message='!'; //  //  $ch = curl_init('http://127.0.0.1/publish?id='.$channel_id); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message)); curl_exec($ch); curl_close($ch); 


Receiving messages in Javascript (jQuery)


There are several ways to subscribe to the channel, the easiest - Ajax request method GET.

 var channelId = subscriber1; //id  var last_etag=0; //   'Etag' var last_time=null; //   'Last-Modified' function new_message() { $.ajax({ url: '/subscribe/' + channelId, type: "GET", dataType: 'json', beforeSend: function(xhr){xhr.setRequestHeader('Etag', last_etag);xhr.setRequestHeader('Last-Modified', last_time);}, success: function(data, status, xhr) { last_etag =xhr.getResponseHeader('Etag'); //    last_etag //   'Etag'  last_time =xhr.getResponseHeader('Last-Modified'); //     last_time //   'Last-Modified'  // -     setTimeout(new_message, 500); //      } }) } new_message(); 

That's all. This chat is cross-browser, does not require additional plug-ins from users and is suitable for projects of any scale. Here's a video chat using this text chat.

Source: https://habr.com/ru/post/252349/


All Articles