All Projects → ollyxar → Websockets Chat

ollyxar / Websockets Chat

Licence: mit
Laravel WebSockets chat

Projects that are alternatives of or similar to Websockets Chat

Atmosphere
Realtime Client Server Framework for the JVM, supporting WebSockets with Cross-Browser Fallbacks
Stars: ✭ 3,552 (+7972.73%)
Mutual labels:  websockets, websocket-server
Seasocks
Simple, small, C++ embeddable webserver with WebSockets support
Stars: ✭ 517 (+1075%)
Mutual labels:  websockets, websocket-server
Django Private Chat
Django one-to-one Websocket-based Asyncio-handled chat, developed by Bearle team
Stars: ✭ 376 (+754.55%)
Mutual labels:  chat, websockets
Websockets
Library for building WebSocket servers and clients in Python
Stars: ✭ 3,724 (+8363.64%)
Mutual labels:  websockets, websocket-server
Ulfius
Web Framework to build REST APIs, Webservices or any HTTP endpoint in C language. Can stream large amount of data, integrate JSON data with Jansson, and create websocket services
Stars: ✭ 666 (+1413.64%)
Mutual labels:  websockets, websocket-server
Saea
SAEA.Socket is a high-performance IOCP framework TCP based on dotnet standard 2.0; Src contains its application test scenarios, such as websocket,rpc, redis driver, MVC WebAPI, lightweight message server, ultra large file transmission, etc. SAEA.Socket是一个高性能IOCP框架的 TCP,基于dotnet standard 2.0;Src中含有其应用测试场景,例如websocket、rpc、redis驱动、MVC WebAPI、轻量级消息服务器、超大文件传输等
Stars: ✭ 318 (+622.73%)
Mutual labels:  chat, websockets
Php Websocket
Simple WebSocket server implemented in PHP.
Stars: ✭ 473 (+975%)
Mutual labels:  websockets, websocket-server
Beast
HTTP and WebSocket built on Boost.Asio in C++11
Stars: ✭ 3,241 (+7265.91%)
Mutual labels:  websockets, websocket-server
Main
a minimal, distraction-free chat application
Stars: ✭ 648 (+1372.73%)
Mutual labels:  chat, websockets
Gwsocket
fast, standalone, language-agnostic WebSocket server RFC6455 compliant
Stars: ✭ 550 (+1150%)
Mutual labels:  websockets, websocket-server
Mercurius
Real-time Messenger for Laravel
Stars: ✭ 309 (+602.27%)
Mutual labels:  chat, websockets
Awesome Websockets
A curated list of Websocket libraries and resources.
Stars: ✭ 850 (+1831.82%)
Mutual labels:  websockets, websocket-server
React Redux Chat
🔥🔥react+redux-chat 模仿实现PC微信聊天系统。
Stars: ✭ 308 (+600%)
Mutual labels:  chat, websockets
Rpc Websockets
JSON-RPC 2.0 implementation over WebSockets for Node.js and JavaScript/TypeScript
Stars: ✭ 344 (+681.82%)
Mutual labels:  chat, websocket-server
Microwebsrv2
The last Micro Web Server for IoTs (MicroPython) or large servers (CPython), that supports WebSockets, routes, template engine and with really optimized architecture (mem allocations, async I/Os). Ready for ESP32, STM32 on Pyboard, Pycom's chipsets (WiPy, LoPy, ...). Robust, efficient and documented!
Stars: ✭ 295 (+570.45%)
Mutual labels:  websockets, websocket-server
Microwebsrv
A micro HTTP Web server that supports WebSockets, html/python language templating and routing handlers, for MicroPython (used on Pycom modules & ESP32)
Stars: ✭ 420 (+854.55%)
Mutual labels:  websockets, websocket-server
LazWebsockets
Websocket Server and Client Library written in Lazarus
Stars: ✭ 51 (+15.91%)
Mutual labels:  websocket-server, websockets
chat-with-deno-and-preact
Chat app with Deno + Preact
Stars: ✭ 27 (-38.64%)
Mutual labels:  chat, websockets
Rockgo
A developing game server framework,based on Entity Component System(ECS).
Stars: ✭ 532 (+1109.09%)
Mutual labels:  websockets, websocket-server
Cowboy
Small, fast, modern HTTP server for Erlang/OTP.
Stars: ✭ 6,533 (+14747.73%)
Mutual labels:  websockets, websocket-server

Laravel WebSocket chat server

Version Downloads License

logo

Requirements

  • Unix (extension pcntl_fork)
  • PHP 7.1+
  • Laravel 5
  • composer

Installing WebSockets Chat

The recommended way to install WebSockets is through Composer.

# Install Composer
curl -sS https://getcomposer.org/installer | php

Next, run the Composer command to install the latest stable version of WebSockets:

php composer.phar require ollyxar/websockets-chat

After updating composer, add the service provider to the providers array in config/app.php

Ollyxar\WSChat\WSChatServiceProvider::class,

Configuration

You can customize variables bellow by adding config-file: websockets-chat.php in the config folder:

parameter description example
handler Handler Class (extends of Worker) \App\MyHandler
host Host (ip) 0.0.0.0
port Port 2083
worker_count Count of forked process 4
use_ssl Used protocol false
cert PEM certificate /etc/nginx/conf.d/wss.pem
pass_phrase PEM certificate pass phrase secret$#%

Extended Handler class

This is example how to use Handler with User authentication. If you have default configuration and file-session-storage you can use this example.

First you have to install auth-helper:

php composer.phar require ollyxar/laravel-auth

Then create your Handler.php:

namespace App;

use Generator;
use Ollyxar\LaravelAuth\FileAuth;
// or you can use RedisAuth if you're storing sessions in the Redis-server:
// use Ollyxar\LaravelAuth\RedisAuth;
use Ollyxar\WebSockets\{
   Frame,
   Handler as Worker,
   Dispatcher
};

/**
 * Class Handler
 * @package App
 */
class Handler extends Worker
{
    /**
     * Connected users
     *
     * @var array
     */
    protected $users = [];

    /**
     * Append connected user
     *
     * @param array $headers
     * @param $socket
     * @return bool
     */
    private function fillUser(array $headers, $socket): bool
    {
        if ($userId = FileAuth::getUserIdByHeaders($headers)) {
            // allow only one connection for worker per user
            if (!in_array($userId, $this->users)) {
                $this->users[(int)$socket] = $userId;
                return true;
            }
        }

        return false;
    }

    /**
     * @param $client
     * @return Generator
     */
    protected function onConnect($client): Generator
    {
        $userName = User::where('id', (int)$this->users[(int)$client])->first()->name;
        yield Dispatcher::async($this->broadcast(Frame::encode(json_encode([
            'type'    => 'system',
            'message' => $userName . ' connected.'
        ]))));
    }

    /**
     * @param array $headers
     * @param $socket
     * @return bool
     */
    protected function validateClient(array $headers, $socket): bool
    {
        return $this->fillUser($headers, $socket);
    }

    /**
     * @param $clientNumber
     * @return Generator
     */
    protected function onClose($clientNumber): Generator
    {
        $user = User::where('id', (int)@$this->users[$clientNumber])->first();
        $userName = data_get($user, 'name', '[GUEST]');

        yield Dispatcher::async($this->broadcast(Frame::encode(json_encode([
            'type'    => 'system',
            'message' => $userName . " disconnected."
        ]))));

        unset($this->users[$clientNumber]);
        yield;
    }

    /**
     * @param string $message
     * @param int $socketId
     * @return Generator
     */
    protected function onClientMessage(string $message, int $socketId): Generator
    {
        $message = json_decode($message);
        $userName = User::where('id', (int)$this->users[$socketId])->first()->name;
        $userMessage = $message->message;

        $response = Frame::encode(json_encode([
            'type'    => 'usermsg',
            'name'    => $userName,
            'message' => $userMessage
        ]));

        yield Dispatcher::async($this->broadcast($response));
    }
}

Then add markup to the front:

<div class="chat-wrapper">
    <div class="message-box" id="message-box"></div>
    <div class="panel">
        <input type="text" name="message" id="message" placeholder="Message"/>
        <button id="send-btn" class="button">Send</button>
    </div>
</div>

And JS code:

var wsUri = "ws://laravel5.dev:2083",
    ws = new WebSocket(wsUri);

ws.onopen = function () {
    var el = document.createElement('div');
    el.classList.add('system-msg');
    el.innerText = 'Connection established';
    document.getElementById('message-box').appendChild(el);
};

document.getElementById('message').addEventListener('keydown', function (e) {
    if (e.keyCode === 13) {
        document.getElementById('send-btn').click();
    }
});

document.getElementById('send-btn').addEventListener('click', function () {
    var mymessage = document.getElementById('message').value;

    if (mymessage === '') {
        alert("Enter Some message Please!");
        return;
    }

    var objDiv = document.getElementById("message-box");
    objDiv.scrollTop = objDiv.scrollHeight;

    var msg = {
        message: mymessage
    };
    ws.send(JSON.stringify(msg));
});

ws.onmessage = function (ev) {
    var msg = JSON.parse(ev.data),
        type = msg.type,
        umsg = msg.message,
        uname = msg.name;

    var el = document.createElement('div');

    if (type === 'usermsg') {
        el.innerHTML = '<span class="user-name">' + uname + '</span> : <span class="user-message">' + umsg + '</span>';
        document.getElementById('message-box').appendChild(el);
    }
    if (type === 'system') {
        el.classList.add('system-msg');
        el.innerText = umsg;
        document.getElementById('message-box').appendChild(el);
    }

    document.getElementById('message').value = '';

    var objDiv = document.getElementById('message-box');
    objDiv.scrollTop = objDiv.scrollHeight;
};

ws.onerror = function (e) {
    var el = document.createElement('div');
    el.classList.add('system-error');
    el.innerText = 'Error Occurred - ' + e.data;
    document.getElementById('message-box').appendChild(el);
};
ws.onclose = function () {
    var el = document.createElement('div');
    el.classList.add('system-msg');
    el.innerText = 'Connection Closed';
    document.getElementById('message-box').appendChild(el);
};

Starting WebSocket Server

php artisan websockets-chat:run

Sending direct message to the server

php artisan websockets-chat:send "Hello from system!"
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].