Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P6)

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P6)

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P6): Establish a Connection Between the Socket.io Client and The Swoole Websocket server

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P6): Establish a Connection Between the Socket.io Client and The Swoole Websocket server

Server transformation plan

After completing the development environment, setting up the back-end Websocket server, and initializing the front-end resources, we then officially started debugging the front-end and back-end interfaces to complete the development of the online chat room function.

The first thing we need to do is to establish a Websocket connection and communication between the client and the server. Here, our Websocket client uses socket.io-client, and the server uses the WebSocket server provided by the Swoole-based LaravelS extension package . socket.io has its own set of connection establishment and data encoding mechanisms, so you must adjust the original Websocket server implementation, otherwise you cannot establish a WebSocket connection.

The LaravelS extension pack is not friendly to the Socket.io client, but another popular Laravel Swoole extension pack Laravel-Swoole has good support for it, and it can even be said that it is a PHP server adaptation of the socket.io client For details, you can refer to its official documentation , so it is natural that we can port this part of its implementation to LaravelS.

The code of this project has been submitted to the Github code repository: https://github.com/nonfu/webchat , you can download the code from here for comparison.

Writing a data parser Parser

The data format sent and received by the socket.io client has its own rules. We need to implement the corresponding data parser on the server according to this rule, in order to decode the received client data before processing the data, and then process it. After that, encode the data before sending it to the client so that the client can parse it correctly.

This part of the logic directly Laravel-Swoole expansion pack copy, first app/services create the directory WebSocket subdirectories for storing WebSocket server-related code, and then the previously created WebSocketHandler handler class to move, at the same time do not forget to change config/laravels.php the profile of WebSocketHandler the path:

'websocket' => [
    'enable' => true,
    'handler' => \App\Services\WebSocket\WebSocketHandler::class,
],

Next, start writing data parser, in app/Services/WebSocket creating an abstract base class directory Parser initialization code as follows:

<?php
/**
 * Data codec abstract base class
 */

namespace App\Services\WebSocket;

use Illuminate\Support\Facades\App;

abstract class Parser
{
    /**
     * Strategy classes need to implement handle method.
     */
    protected $strategies = [];

    /**
     * Execute strategies before decoding payload.
     * If return value is true will skip decoding.
     *
     * @param \Swoole\WebSocket\Server $server
     * @param \Swoole\WebSocket\Frame $frame
     *
     * @return boolean
     */
    public function execute($server, $frame)
    {
        $skip = false;

        foreach ($this->strategies as $strategy) {
            $result = App::call(
                $strategy . '@handle',
                [
                    'server' => $server,
                    'frame' => $frame,
                ]
            );
            if ($result === true) {
                $skip = true;
                break;
            }
        }

        return $skip;
    }

    /**
     * Encode output payload for websocket push.
     *
     * @param string $event
     * @param mixed $data
     *
     * @return mixed
     */
    abstract public function encode(string $event, $data);

    /**
     * Input message on websocket connected.
     * Define and return event name and payload data here.
     *
     * @param \Swoole\Websocket\Frame $frame
     *
     * @return array
     */
    abstract public function decode($frame);
}

Then WebSocket create a subdirectory under the directory SocketIO used to store the relevant code to interact with the client socket.io. The first is the data parser corresponding to the socket.io client SocketIOParser. This class inherits from Parser:

<?php
/**
 * Socket.io corresponding data codec
 */

namespace App\Services\WebSocket\SocketIO;

use App\Services\WebSocket\Parser;
use App\Services\WebSocket\SocketIO\Strategies\HeartbeatStrategy;

class SocketIOParser extends Parser
{
    /**
     * Strategy classes need to implement handle method.
     */
    protected $strategies = [
        HeartbeatStrategy::class,
    ];

    /**
     * Encode output payload for websocket push.
     *
     * @param string $event
     * @param mixed $data
     *
     * @return mixed
     */
    public function encode(string $event, $data)
    {
        $packet = Packet::MESSAGE . Packet::EVENT;
        $shouldEncode = is_array($data) || is_object($data);
        $data = $shouldEncode ? json_encode($data) : $data;
        $format = $shouldEncode ? '["%s",%s]' : '["%s","%s"]';

        return $packet . sprintf($format, $event, $data);
    }

    /**
     * Decode message from websocket client.
     * Define and return payload here.
     *
     * @param \Swoole\Websocket\Frame $frame
     *
     * @return array
     */
    public function decode($frame)
    {
        $payload = Packet::getPayload($frame->data);

        return [
            'event' => $payload['event'] ?? null,
            'data' => $payload['data'] ?? null,
        ];
    }
}

This is used inside the package Packet type communication data analysis processing:

<?php
/**
 * Socket.io communication data parsing underlying class
 */

namespace App\Services\WebSocket\SocketIO;

class Packet
{
    /**
     * Socket.io packet type `open`.
     */
    const OPEN = 0;

    /**
     * Socket.io packet type `close`.
     */
    const CLOSE = 1;

    /**
     * Socket.io packet type `ping`.
     */
    const PING = 2;

    /**
     * Socket.io packet type `pong`.
     */
    const PONG = 3;

    /**
     * Socket.io packet type `message`.
     */
    const MESSAGE = 4;

    /**
     * Socket.io packet type 'upgrade'
     */
    const UPGRADE = 5;

    /**
     * Socket.io packet type `noop`.
     */
    const NOOP = 6;

    /**
     * Engine.io packet type `connect`.
     */
    const CONNECT = 0;

    /**
     * Engine.io packet type `disconnect`.
     */
    const DISCONNECT = 1;

    /**
     * Engine.io packet type `event`.
     */
    const EVENT = 2;

    /**
     * Engine.io packet type `ack`.
     */
    const ACK = 3;

    /**
     * Engine.io packet type `error`.
     */
    const ERROR = 4;

    /**
     * Engine.io packet type 'binary event'
     */
    const BINARY_EVENT = 5;

    /**
     * Engine.io packet type `binary ack`. For acks with binary arguments.
     */
    const BINARY_ACK = 6;

    /**
     * Socket.io packet types.
     */
    public static $socketTypes = [
        0 => 'OPEN',
        1 => 'CLOSE',
        2 => 'PING',
        3 => 'PONG',
        4 => 'MESSAGE',
        5 => 'UPGRADE',
        6 => 'NOOP',
    ];

    /**
     * Engine.io packet types.
     */
    public static $engineTypes = [
        0 => 'CONNECT',
        1 => 'DISCONNECT',
        2 => 'EVENT',
        3 => 'ACK',
        4 => 'ERROR',
        5 => 'BINARY_EVENT',
        6 => 'BINARY_ACK',
    ];

    /**
     * Get socket packet type of a raw payload.
     *
     * @param string $packet
     *
     * @return int|null
     */
    public static function getSocketType(string $packet)
    {
        $type = $packet[0] ?? null;

        if (! array_key_exists($type, static::$socketTypes)) {
            return null;
        }

        return (int) $type;
    }

    /**
     * Get data packet from a raw payload.
     *
     * @param string $packet
     *
     * @return array|null
     */
    public static function getPayload(string $packet)
    {
        $packet = trim($packet);
        $start = strpos($packet, '[');

        if ($start === false || substr($packet, -1) !== ']') {
            return null;
        }

        $data = substr($packet, $start, strlen($packet) - $start);
        $data = json_decode($data, true);

        if (is_null($data)) {
            return null;
        }

        return [
            'event' => $data[0],
            'data' => $data[1] ?? null,
        ];
    }

    /**
     * Return if a socket packet belongs to specific type.
     *
     * @param $packet
     * @param string $typeName
     *
     * @return bool
     */
    public static function isSocketType($packet, string $typeName)
    {
        $type = array_search(strtoupper($typeName), static::$socketTypes);

        if ($type === false) {
            return false;
        }

        return static::getSocketType($packet) === $type;
    }
}

In addition SocketIOParser also introduced strategy for processing the heartbeat connection, so-called heartbeat connection refers to the connection length in order to maintain a connection for communication at predetermined time intervals, which typically are not required for communication processing can be ignored, and there is such a made.

Heartbeat connection policy classes are held in SocketIO/Strategies the directory:

<?php
/**
 * Heartbeat connection processing strategy class
 */

namespace App\Services\WebSocket\SocketIO\Strategies;

use App\Services\WebSocket\SocketIO\Packet;

class HeartbeatStrategy
{
    /**
     * If return value is true will skip decoding.
     *
     * @param \Swoole\WebSocket\Server $server
     * @param \Swoole\WebSocket\Frame $frame
     *
     * @return boolean
     */
    public function handle($server, $frame)
    {
        $packet = $frame->data;
        $packetLength = strlen($packet);
        $payload = '';

        if (Packet::getPayload($packet)) {
            return false;
        }

        if ($isPing = Packet::isSocketType($packet, 'ping')) {
            $payload .= Packet::PONG;
        }

        if ($isPing && $packetLength > 1) {
            $payload .= substr($packet, 1, $packetLength - 1);
        }

        if ($isPing) {
            $server->push($frame->fd, $payload);
        }

        return true;
    }
}

At this point, our communication data parser is all completed. Next, let's look at the encapsulated communication data sending class.

Writing data sending classes Pusher

The reconstructed WebSocketHandler class will bear only routing and controller functions, to business logic related services will be peeled off to complete a separate service unit, comprising sending data, because we need to be uniform encapsulation processing, so that the customer can be End resolution. In the app/Services/WebSocket creation directory Pusher class for data transmission:

<?php
/**
 * Communication data transmission class
 */

namespace App\Services\WebSocket;


class Pusher
{
    /**
     * @var \Swoole\Websocket\Server
     */
    protected $server;

    /**
     * @var int
     */
    protected $opcode;

    /**
     * @var int
     */
    protected $sender;

    /**
     * @var array
     */
    protected $descriptors;

    /**
     * @var bool
     */
    protected $broadcast;

    /**
     * @var bool
     */
    protected $assigned;

    /**
     * @var string
     */
    protected $event;

    /**
     * @var mixed|null
     */
    protected $message;

    /**
     * Push constructor.
     *
     * @param int $opcode
     * @param int $sender
     * @param array $descriptors
     * @param bool $broadcast
     * @param bool $assigned
     * @param string $event
     * @param mixed|null $message
     * @param \Swoole\Websocket\Server
     */
    protected function __construct(
        int $opcode,
        int $sender,
        array $descriptors,
        bool $broadcast,
        bool $assigned,
        string $event,
        $message = null,
        $server
    )
    {
        $this->opcode = $opcode;
        $this->sender = $sender;
        $this->descriptors = $descriptors;
        $this->broadcast = $broadcast;
        $this->assigned = $assigned;
        $this->event = $event;
        $this->message = $message;
        $this->server = $server;
    }

    /**
     * Static constructor
     *
     * @param array $data
     * @param \Swoole\Websocket\Server $server
     *
     * @return Pusher
     */
    public static function make(array $data, $server)
    {
        return new static(
            $data['opcode'] ?? 1,
            $data['sender'] ?? 0,
            $data['fds'] ?? [],
            $data['broadcast'] ?? false,
            $data['assigned'] ?? false,
            $data['event'] ?? null,
            $data['message'] ?? null,
            $server
        );
    }

    /**
     * @return int
     */
    public function getOpcode(): int
    {
        return $this->opcode;
    }

    /**
     * @return int
     */
    public function getSender(): int
    {
        return $this->sender;
    }

    /**
     * @return array
     */
    public function getDescriptors(): array
    {
        return $this->descriptors;
    }

    /**
     * @param int $descriptor
     *
     * @return self
     */
    public function addDescriptor($descriptor): self
    {
        return $this->addDescriptors([$descriptor]);
    }

    /**
     * @param array $descriptors
     *
     * @return self
     */
    public function addDescriptors(array $descriptors): self
    {
        $this->descriptors = array_values(
            array_unique(
                array_merge($this->descriptors, $descriptors)
            )
        );

        return $this;
    }

    /**
     * @param int $descriptor
     *
     * @return bool
     */
    public function hasDescriptor(int $descriptor): bool
    {
        return in_array($descriptor, $this->descriptors);
    }

    /**
     * @return bool
     */
    public function isBroadcast(): bool
    {
        return $this->broadcast;
    }

    /**
     * @return bool
     */
    public function isAssigned(): bool
    {
        return $this->assigned;
    }

    /**
     * @return string
     */
    public function getEvent(): string
    {
        return $this->event;
    }

    /**
     * @return mixed|null
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * @return \Swoole\Websocket\Server
     */
    public function getServer()
    {
        return $this->server;
    }

    /**
     * @return bool
     */
    public function shouldBroadcast(): bool
    {
        return $this->broadcast && empty($this->descriptors) && ! $this->assigned;
    }

    /**
     * Returns all descriptors that are websocket
     *
     * @param \Swoole\Connection\Iterator $descriptors
     *
     * @return array
     */
    protected function getWebsocketConnections(): array
    {
        return array_filter(iterator_to_array($this->server->connections), function ($fd) {
            return $this->server->isEstablished($fd);
        });
    }

    /**
     * @param int $fd
     *
     * @return bool
     */
    public function shouldPushToDescriptor(int $fd): bool
    {
        if (! $this->server->isEstablished($fd)) {
            return false;
        }

        return $this->broadcast ? $this->sender !== (int) $fd : true;
    }

    /**
     * Push message to related descriptors
     *
     * @param mixed $payload
     *
     * @return void
     */
    public function push($payload): void
    {
        // attach sender if not broadcast
        if (! $this->broadcast && $this->sender && ! $this->hasDescriptor($this->sender)) {
            $this->addDescriptor($this->sender);
        }

        // check if to broadcast to other clients
        if ($this->shouldBroadcast()) {
            $this->addDescriptors($this->getWebsocketConnections());
        }

        // push message to designated fds
        foreach ($this->descriptors as $descriptor) {
            if ($this->shouldPushToDescriptor($descriptor)) {
                $this->server->push($descriptor, $payload, $this->opcode);
            }
        }
    }
}

This class is mainly used for business logic processing sent to the client after data processing, including data parsing and unified encapsulation, whether to broadcast, etc.

Writing WebSocket service class

In addition to simple data receiving and sending, our online chat room has many other complex functions, so it is necessary to create a separate service class to implement these functions, such as room join and exit, user authentication and acquisition, data transmission and broadcasting, where the final will call Pusher the class to send data, it can be said that the service class is the core of the WebSocket back-end services, but this tutorial to simplify this section, just copy over an empty placeholder class, more Multifunctionality will be gradually added in subsequent tutorials:

<?php
namespace App\Services\WebSocket;

class WebSocket
{
    const PUSH_ACTION = 'push';
    const EVENT_CONNECT = 'connect';
    const USER_PREFIX = 'uid_';

    /**
     * Determine if to broadcast.
     *
     * @var boolean
     */
    protected $isBroadcast = false;

    /**
     * Scoket sender's fd.
     *
     * @var integer
     */
    protected $sender;

    /**
     * Recepient's fd or room name.
     *
     * @var array
     */
    protected $to = [];

    /**
     * Websocket event callbacks.
     *
     * @var array
     */
    protected $callbacks = [];
}

In this tutorial, in order to simplify the process, we WebSocketHandler directly call the Pusher class to send data to the client to quickly demonstrate establish WebSocket communication connection.

Rewrite WebSocketHandler processors

Finally, we re-implement the code according to the new structure of WebSocketHandler the processor onOpen and onMessage method:

<?php
/**
 * WebSocket service communication processor class
 * Author: College Jun
 */
 
namespace App\Services\WebSocket;

use App\Services\WebSocket\SocketIO\SocketIOParser;
use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
use Illuminate\Support\Facades\Log;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;

class WebSocketHandler implements WebSocketHandlerInterface
{
    /**
     * @var WebSocket
     */
    protected $websocket;
    /**
     * @var Parser
     */
    protected $parser;

    public function __construct()
    {
        $this->websocket = app(WebSocket::class);
        $this->parser = app(SocketIOParser::class);

    }

    // Triggered when the connection is established
    public function onOpen(Server $server, Request $request)
    {
        if (!request()->input('sid')) {
            // Initialize the connection information to adapt socket.io-client, this code cannot be omitted, otherwise the connection cannot be established
            $payload = json_encode([
                'sid' => base64_encode(uniqid()),
                'upgrades' => [],
                'pingInterval' => config('laravels.swoole.heartbeat_idle_time') * 1000,
                'pingTimeout' => config('laravels.swoole.heartbeat_check_interval') * 1000,
            ]);
            $initPayload = Packet::OPEN . $payload;
            $connectPayload = Packet::MESSAGE . Packet::CONNECT;
            $server->push($request->fd, $initPayload);
            $server->push($request->fd, $connectPayload);
        }
    
        Log::info('WebSocket Connection establishment:' . $request->fd);
        $payload = [
            'sender'    => $request->fd,
            'fds'       => [$request->fd],
            'broadcast' => false,
            'assigned'  => false,
            'event'     => 'message',
            'message'   => 'Welcome to chat room',
        ];
        $pusher = Pusher::make($payload, $server);
        $pusher->push($this->parser->encode($pusher->getEvent(), $pusher->getMessage()));
    }

    // Triggered when a message is received
    public function onMessage(Server $server, Frame $frame)
    {
        // $frame->fd Is the client id,$frame->data Is the data sent by the client
        Log::info("From {$frame->fd} Received data: {$frame->data}");
        if ($this->parser->execute($server, $frame)) {
            // Skip heartbeat connection processing
            return;
        }
        $payload = $this->parser->decode($frame);
        ['event' => $event, 'data' => $data] = $payload;
        $payload = [
            'sender' => $frame->fd,
            'fds'    => [$frame->fd],
            'broadcast' => false,
            'assigned'  => false,
            'event'     => $event,
            'message'   => $data,
        ];
        $pusher = Pusher::make($payload, $server);
        $pusher->push($this->parser->encode($pusher->getEvent(), $pusher->getMessage()));
    }

    // Triggered when the connection is closed
    public function onClose(Server $server, $fd, $reactorId)
    {
        Log::info('WebSocket Connection closed:' . $fd);
    }
}

First initialized in the constructor $websocket and $parser attributes, then the connection establishment callback method onOpen , it is determined request data contains sid fields not included the need to send connection initiation information to the client in order to successfully establish WebSocket connection, here we also specify the heartbeat interval time and time-out, the appropriate, we also need to profile config/laravels.php the swoole new configuration the following two items:

'heartbeat_idle_time' => 600,
'heartbeat_check_interval' => 60,

Then call the Pusher class push method to send a welcome message encoded in order to be resolved socket.io end customers.

In the method of the callback message is received onMessage, the first call the Parser class execute method determines whether the heartbeat connection, if the heartbeat connection is skipped if not treated, otherwise decoding the received information, after a simple treatment, and then through Pusher the class push method is sent back to the client.

At this point, the Swoole WebSocket server connection establishment and simple communication logic adapted to the socket.io client have been initially implemented. Next, we need to restart the Swoole WebSocket server for the code to take effect:

bin/laravels restart
socket.io client code tuning

Finally, we revise down socket.io client connection code, open resources/js/socket.js modify the connection establishment code is as follows:

import io from 'socket.io-client';
const socket = io('http://webchats.test', {
    path: '/ws',
    transports: ['websocket']
});
export default socket;

Here we set the server address to be driven by the Swoole HTTP server http://webchats.test, then set the path /ws to connect to the Swoole WebSocket server, and finally set the transport layer protocol to websocket replace the default long polling(polling) mechanism.

In addition Vue front-end components and view files and JavaScript files main entrance app.js also made some minor adjustments, the corresponding code to the code repository https://github.com/nonfu/webchat latest submitted version shall prevail, as in app.js, we printed Log of whether the Socket connection is established:

socket.on('connect', async () => {
    console.log('websocket connected: ' + socket.connected);
    ...

Next, we run npm run dev recompiled resources, access the browser http://webchats.test, you can see through F12 WebSocket connection establishment and communication of the data.

In the console Consoletab you can also see the following logs:

websocket connected: true

Indicates that the connection was established successfully.

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P14)

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P14)

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P14): Send a Picture Message

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P14): Send a Picture Message

In the last tutorial we demonstrated the release of text/emotional messages in chat rooms. Today we will look at how to post picture messages.

Front-end interaction code

We started from the front end assembly, assembly in a chat room Chat.Vue, the client core logic to send pictures located fileup approach, we need to be adjusted to fit the rear end of the original code based interface Laravel + Swoole of:

fileup() {
    const that = this;
    const file1 = document.getElementById('inputFile').files[0];
    if (file1) {
      const formdata = new window.FormData();
      formdata.append('file', file1);
      formdata.append('api_token', this.auth_token);
      formdata.append('roomid', that.roomid);
      this.$store.dispatch('uploadImg', formdata);
      const fr = new window.FileReader();
      fr.onload = function () {
        const obj = {
          username: that.userid,
          src: that.src,
          img: fr.result,
          msg: '',
          roomid: that.roomid,
          time: new Date(),
          api_token: that.auth_token
        };
        socket.emit('message', obj);
      };
      fr.readAsDataURL(file1);
      this.$nextTick(() => {
        this.container.scrollTop = 10000;
      });
    } else {
      console.log('Must have file');
    }
},

When we click on the camera icon in the chat room, the image upload window will pop up:

After selecting the picture, it will call the above fileup method to upload pictures.

It involves two logic: first calls the back-end interface to upload pictures based on the HTTP protocol and save the message to the messages table, it will send a message to Websocket server after a successful upload, and then by Websocket server broadcasts a message to all online users.

The upload image corresponds to this line of code:

this.$store.dispatch('uploadImg', formdata);

The final call to the back-end interface code is located resources/js/api/server.js in:

// upload image
postUploadFile: data => Axios.post('/file/uploadimg', data, {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}),

We will write this interface in the backend shortly.

Sending a picture message based on Websocket corresponds to this line of code:

socket.emit('message', obj);

This is no different than sending a text message before the code is simply obj there to add a imgfield only.

Image upload interface

Next, we write an image upload interface on the Laravel backend.

In the routes/api.php new route file/uploadimg:

Route::middleware('auth:api')->group(function () {
    ...
    Route::post('/file/uploadimg', '[email protected]');
}

Then create the controller with Artisan commands FileController:

php artisan make:controller FileController

In the newly generated file controller app/Http/Controllers/FileController.php in preparation uploadImage codes are as follows:

<?php
namespace App\Http\Controllers;

use App\Message;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{
    public function uploadImage(Request $request)
    {
        if (!$request->hasFile('file') || !$request->file('file')->isValid() || !$request->has('roomid')) {
            return response()->json([
                'data' => [
                    'errno' => 500,
                    'msg'   => 'Invalid parameter (room number/picture file is empty or invalid)'
                ]
            ]);
        }
        $image = $request->file('file');
        $time = time();
        $filename = md5($time . mt_rand(0, 10000)) . '.' . $image->extension();
        $path = $image->storeAs('images/' . date('Y/m/d', $time), $filename, ['disk' => 'public']);
        if ($path) {
            // If the picture is uploaded successfully, the corresponding picture message is saved to the messages table
            $message = new Message();
            $message->user_id = auth('api')->id();
            $message->room_id = $request->post('roomid');
            $message->msg = '';  // Text message left blank
            $message->img = Storage::disk('public')->url($path);
            $message->created_at = Carbon::now();
            $message->save();
            return response()->json([
                'data' => [
                    'errno' => 200,
                    'msg'   => 'Saved successfully'
                ]
            ]);
        } else {
            return response()->json([
                'data' => [
                    'errno' => 500,
                    'msg'   => 'File upload failed, please try again'
                ]
            ]);
        }
    }
}

This mainly involves image upload and message saving logic. Because we will save the picture to the storage/public next directory, in order to let the picture can be requested through the Web URL, you need to storage create a soft catalog:

php artisan storage:link
Websocket server broadcast

Finally, we in routes/websocket.php the messagechannel complementary picture message processing logic:

WebsocketProxy::on('message', function (WebSocket $websocket, $data) {
    ...
    // Get message content
    $msg = $data['msg'];
    $img = $data['img'];
    $roomId = intval($data['roomid']);
    $time = $data['time'];
    // Message content (including pictures) or room number cannot be empty
    if((empty($msg)  && empty($img))|| empty($roomId)) {
        return;
    }
    // Record log
    Log::info($user->name . 'in the room' . $roomId . 'Post message: ' . $msg);
    // Save messages to the database (except for picture messages, because they were saved during the upload)
    if (empty($img)) {
        $message = new Message();
        $message->user_id = $user->id;
        $message->room_id = $roomId;
        $message->msg = $msg;  // Text message
        $message->img = '';  // Picture message left blank
        $message->created_at = Carbon::now();
        $message->save();
    }
    // Broadcast messages to all users in the room
    $room = Count::$ROOMLIST[$roomId];
    $messageData = [
        'userid' => $user->email,
        'username' => $user->name,
        'src' => $user->avatar,
        'msg' => $msg,
        'img' => $img,
        'roomid' => $roomId,
        'time' => $time
    ];
    $websocket->to($room)->emit('message', $messageData);
    ...

Very simple, just add the picture message field uploaded by the client to the field of the previous broadcast message, without any other logic.

At this point, we can complete the front-end and back-end code for image message sending. Next, we test the sending of image messages on the chat room interface.

Test image message release

Before you start, recompile the front-end resources:

npm run dev

Make front-end code changes take effect. And restart Swoole HTTP and WebSocket server:

bin/laravels restart

Let the backend code changes take effect.

Then, open the chat room in Chrome and Firefox browsers, log in and enter the same room, you can send picture messages to each other in real time:

At this point, we have completed the main function of the chat room. Next, we will optimize the project code, especially the performance and elegance of the back-end WebSocket communication.

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P4)

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P4)

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P4): Front-end Resource Initialization

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P4): Front-end Resource Initialization

As said at the beginning , the front-end interface of this practical tutorial will be based on the chat room project implemented by the front-end technology stack https://github.com/hua1995116/webchat in order to focus on the development of chat room functions based on Swoole for the convenience of introduction, it will be called Vue-Webchat.

However, Vue-Webchat's front and back ends are implemented based on JavaScript. The front end uses the Vue framework, the back end uses the Express framework, the database uses MongoDB , and the front and back ends of WebSocket communication are based on Socket.io. In the project, we want to use the Laravel framework as the backend to store data in the MySQL database, and the WebSocket server is implemented based on Swoole. In addition, we also want to use Laravel Mix provided by Laravel as a front-end resource compilation tool to replace the native Webpack, so the original front-end code must be appropriately modified.

Front-end code for this project has been submitted to the Github repository: https://github.com/nonfu/webchat.

Front-end directory structure migration

In the Vue-Webchat this project, located in the front-end source code src directory:

Let's delete project Laravel webchat of resources/js all files in a directory, then the Vue-Webchat of src directory migrated:

Here I make the adjustment on the part of the directory structure, such as the original project static/css/reset.css moved to resources/css/reset.css, the original project src/styles style under the code integrated into resources/sass/app.scss in order to better fit Laravel project directory structure. In addition, I will be the original project src directory App.vue and BaseTransition.vue files to the resources/js/layout directory, the original project src directory under the view subdirectory rename pages, this is just personal preference, of course, the corresponding need to modify all of the introduction of the file path.

Further, a front end JavaScript file entry main.js for renaming app.js.

Front view entry file

The front-end view entry file of the original project is located in the root directory, index.html and the view entry file of this project is located at resources/views/index.blade.php:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />

    <link rel="icon" type="image/x-icon" href="/favicon.ico">

    <title>Laravel学院在线聊天室</title>

    <script type='text/javascript'>
        window.Laravel = <?php echo json_encode(['csrfToken' => csrf_token(),]); ?>
    </script>
</head>
<body>
    <div id="app"></div>
    <script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
</body>
</html>

Accordingly, the need to routes/web.php route the file to adjust the default home page view template:

Route::get('/', function () {
    return view('index');
});
Front-end code adjustment

Next, let's focus on the modifications made to the front-end code to fit the Laravel back-end framework and the Swoole WebSocket server.

Interaction with back-end interface

Interaction with back-end interfaces are packaged in a unified resources/js/api directory, in axios.js the base package provides a library of Axios, and all back-end interface calls are located in server.js, where we need to axios.js be adjusted, adding CSRF Token request header:

import axios from 'axios';
const baseURL = '/api/';

const instance = axios.create();

instance.defaults.timeout = 30000; // 30s timeout on all interfaces
instance.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

// CSRF Token for all request headers
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
    instance.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

...

The routing and processing logic that specifically calls the back-end interface is ignored first, and then debug one by one when developing specific functions later.

Interaction with WebSocket server

Vue-Webchat project-based socket.io-client libraries to communicate as a client and WebSocket server, where we follow the client program, but the need to modify the connection configuration, back-end configuration changes to Swoole WebSocket server, modify the resources/js/socket.js code as follows:

// WebSocket request via Socket.io client
import io from 'socket.io-client'
const socket = io.connect(process.env.APP_URL + ':' + process.env.LARAVELS_LISTEN_PORT + '/ws/')
export default socket

And axios as specific call this socket module where the first matter, the development of specific functions to back one by one when debugging.

Adjustment of alias paths

Vue-Webchat item view upon introduction assembly and the module configuration @ path alias, such that:

import {queryString} from '@utils/queryString';

This project canceled this configuration and was introduced directly through relative paths:

import {queryString} from './utils/queryString';

All involve @ local path references should be adjusted, mainly in the pages Vue components under a subdirectory.

Front-end style compilation adjustments

As mentioned earlier, JavaScript files of this project is the entrance app.js, CSS resource file in my original project introduced here out of all, integrated into the webpack.mix.js lower compiled by Laravel Mix:

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .styles([
        'resources/css/reset.css',
        'public/css/app.css',
        'node_modules/muse-ui/dist/muse-ui.css'
    ], 'public/css/app.css');

Add front-end dependencies to package.json

Next, we add the front-end code involved in all new dependencies to the project under the root directory package.json in which:

"devDependencies": {
    "axios": "^0.18",
    "cross-env": "^5.1",
    "file-loader": "^4.2.0",
    "jquery": "^3.2",
    "laravel-mix": "^4.0.7",
    "lodash": "^4.17.5",
    "muse-ui": "^3.0.2",
    "popper.js": "^1.12",
    "resolve-url-loader": "^2.3.1",
    "sass": "^1.23.1",
    "sass-loader": "7.*",
    "socket.io-client": "^2.3.0",
    "stylus": "^0.54.7",
    "stylus-loader": "^3.0.2",
    "timers": "^0.1.1",
    "url-loader": "^2.2.0",
    "vivus": "^0.4.5",
    "vue": "^2.6.10",
    "vue-cropper": "^0.4.9",
    "vue-picture-preview": "^1.3.0",
    "vue-router": "^3.1.2",
    "vue-style-loader": "^4.1.2",
    "vue-template-compiler": "^2.6.10",
    "vuex": "^3.1.1",
    "xss-filters-es6": "^1.0.0"
}

And then run the npm install install all front-end dependent libraries.

Of course, all the above front-end code migrations and adjustments have been submitted to the Github repository, you can download the corresponding resources directly to the local here: https://github.com/nonfu/webchat.

Compile front-end resources

Finally, in the root directory of the project npm run dev to compile all of these resources through the front Laravel Mix:

After the compilation is successful, next, we will start debugging the interaction between the front-end interface and the back-end interface, which will be explained in subsequent tutorials.

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P5)

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P5)

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P5): Homestead Development Environment Initialization

Building a Live Online Chat Room Based on Laravel + Swoole + Vue (P5): Homestead Development Environment Initialization

Integrating the Swoole environment in Homestead, of course, it is not necessary to manually install the Swoole extension after rebuilding Homestead, or to manually configure the Nginx reverse proxy based on the Swoole HTTP server driver every time you create a new site. This is too laborious, we It is entirely possible to automate these operations through configuration based on the extension mechanism provided by Homestead. Next, the Academy takes the Mac environment + Homestead 8.1.0 version as an example to demonstrate how to integrate Laravel + Swoole development environment in Homestead.

Install Swoole Extension

Installation script

To use Swoole, you must first install PHP extensions corresponding to the global share of Homestead, for example, into the Homestead project root directory, open the after.sh file, add the following command to install extensions enabled Swoole the end of the file:

# Install Swoole Extension
sudo pecl install swoole
sudo echo "extension=swoole.so" > /tmp/swoole.ini
sudo cp /tmp/swoole.ini /etc/php/7.3/mods-available/swoole.ini    # Write directly without permission error, so here is done through the tmp directory
sudo ln -fs /etc/php/7.3/mods-available/swoole.ini /etc/php/7.3/cli/conf.d/20-swoole.ini

Note: Homestead uses the default PHP version of 7.3, so the Swoole extension I installed applies to 7.3 by default. If your Homestead defaults to another version of PHP, you need to adjust the corresponding PHP version directory to enable the extension.

after.sh The script will run after the Homestead refactoring (provision), so every time you refactor the Homestead development environment, the Swoole extension will be reinstalled, so that we don't need to log in to the Homestead virtual machine and install it manually.

Check if the installation was successful

Next, we run Homestead the project directory vagrant reload --provision restart Homestead, then by homestead ssh log on to the virtual machine, run php -m to see expansion is enabled, see swoole in the list, said the installation was successful:

At this point, the Swoole extension has been successfully installed, indicating that we can use the various APIs provided by the Swoole extension package in the Homestead virtual machine.

Automatically configure Swoole type sites

However, we know, Homestead also has a very powerful feature that can be configured Homestead.yaml to achieve the configuration file directory mapping host and the virtual machines, as well as the corresponding Nginx virtual hosts and automatically create and configure the database, we can extend the functionality to support Swoole type sites, of course you can, next, the academy will show you how to achieve it.

Homestead Site Initialization Process

Before that, let's look briefly at startup Homestead virtual machine at the entrance of the file vagrantfile, the configuration file is loaded Homestead and Homestead master file:

...

homesteadYamlPath = confDir + "/Homestead.yaml"
homesteadJsonPath = confDir + "/Homestead.json"
afterScriptPath = confDir + "/after.sh"
customizationScriptPath = confDir + "/user-customizations.sh"
aliasesPath = confDir + "/aliases"

require File.expand_path(File.dirname(__FILE__) + '/scripts/homestead.rb')

...

And then reads the configuration file by the Homestead.configure analytical method and initialize these configurations:

...

if File.exist? homesteadYamlPath then
    settings = YAML::load(File.read(homesteadYamlPath))
elsif File.exist? homesteadJsonPath then
    settings = JSON::parse(File.read(homesteadJsonPath))
else
    abort "Homestead settings file not found in #{confDir}"
end

Homestead.configure(config, settings)

...

Homestead.configure The method defined in above-incorporated scripts/homestead.rb documents, Homestead.yaml in all configurations are here parsed and mapped onto the corresponding Vagrant configuration, a virtual machine implementing a custom configuration, since Vagrant based Ruby implementation, the code here are prepared by Ruby.

Homestead natively supports the following types of sites:

  • laravel (default)
  • apache
  • apigility
  • expressive
  • proxy
  • SilverStripe
  • statamic
  • Symfony2
  • symfony4
  • zf

Does not contain Swoole, so we need to configure Homestead support swoole type sites, sites of different types of databases and directories mapping configuration is the same, except that Nginx virtual host configuration, so we focus on sitesparsing the configuration items. In Homestead.configure find the following line method:

# Install All The Configured Nginx Sites
if settings.include? 'sites'

Nginx site configuration initialization start from here, Homestead will cycle through all the sites configuration starts to initialize each site:

settings['sites'].each do |site|

The other sharing processes are the same, mainly to see how different types of sites handle them:

# Convert the site & any options to an array of arguments passed to the
# specific site type script (defaults to laravel)
s.path = script_dir + "/site-types/#{type}.sh"
s.args = [
    site['map'],                # $1
    site['to'],                 # $2
    site['port'] ||= http_port, # $3
    site['ssl'] ||= https_port, # $4
    site['php'] ||= '7.3',      # $5
    params ||= '',              # $6
    site['xhgui'] ||= '',       # $7
    site['exec'] ||= 'false',   # $8
    headers ||= '',             # $9
    rewrites ||= ''             # $10
]

Here's #{type} corresponding precisely Homestead.yaml the sites type of site configuration items in the configuration type, all supported site type configuration scripts are located in scripts/site-types the directory:

Homestead will be Homestead.yaml the site configuration items in the configuration file is transferred to read different types of sites in the script file, creating and initializing Nginx virtual host file, and each configuration item corresponds to the parameters of a number to refer to in the script file, with this understanding, you should know how to customize your new site type in Homestead.

Create Swoole Site Script

We follow suit, and in scripts/site-types the new directory a swoole.sh file, and write the script reads as follows:

#!/usr/bin/env bash

declare -A params=$6       # Create an associative array
declare -A headers=${9}    # Create an associative array
declare -A rewrites=${10}  # Create an associative array
paramsTXT=""
if [ -n "$6" ]; then
   for element in "${!params[@]}"
   do
      paramsTXT="${paramsTXT}
      fastcgi_param ${element} ${params[$element]};"
   done
fi
headersTXT=""
if [ -n "${9}" ]; then
   for element in "${!headers[@]}"
   do
      headersTXT="${headersTXT}
      add_header ${element} ${headers[$element]};"
   done
fi
rewritesTXT=""
if [ -n "${10}" ]; then
   for element in "${!rewrites[@]}"
   do
      rewritesTXT="${rewritesTXT}
      location ~ ${element} { if (!-f \$request_filename) { return 301 ${rewrites[$element]}; } }"
   done
fi

if [ "$7" = "true" ]
then configureXhgui="
location /xhgui {
        try_files \$uri \$uri/ /xhgui/index.php?\$args;
}
"
else configureXhgui=""
fi

# 设置 WebSocket 服务器名称
websocketServer=`echo "${1}" | sed "s/^\(.*\)\.test$/\1/g"`  
    
block="map \$http_upgrade \$connection_upgrade {
    default upgrade;
    ''      close;
}

upstream $websocketServer {
    # Connect IP:Port
    server 127.0.0.1:5200 weight=5 max_fails=3 fail_timeout=30s;
    keepalive 16;
}

server {
    listen ${3:-80};
    listen ${4:-443} ssl http2;
    server_name $1;
    root \"$2\";

    index index.html index.htm index.php;

    charset utf-8;

    $rewritesTXT

    location / {
        try_files \$uri @$websocketServer;
        $headersTXT
    }

    $configureXhgui

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/$1-error.log error;

    sendfile off;

    client_max_body_size 100m;

    location ~ \.php$ {
        return 404;
    }

    # Handle WebSocket communication
    location ^~ /ws/ {
        # proxy_connect_timeout 60s;
        # proxy_send_timeout 60s;
        # proxy_read_timeout: Nginx will close the connection if the proxied server does not send data to Nginx in 60 seconds; At the same time, this close behavior is also affected by heartbeat setting of Swoole.
        # proxy_read_timeout 60s;
        proxy_http_version 1.1;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Real-PORT \$remote_port;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header Host \$http_host;
        proxy_set_header Scheme \$scheme;
        proxy_set_header Server-Protocol \$server_protocol;
        proxy_set_header Server-Name \$server_name;
        proxy_set_header Server-Addr \$server_addr;
        proxy_set_header Server-Port \$server_port;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection \$connection_upgrade;
        proxy_pass http://$websocketServer;
    }

    location @$websocketServer {
        # proxy_connect_timeout 60s;
        # proxy_send_timeout 60s;
        # proxy_read_timeout 60s;
        proxy_http_version 1.1;
        proxy_set_header Connection \"\";
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Real-PORT \$remote_port;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header Host \$http_host;
        proxy_set_header Scheme \$scheme;
        proxy_set_header Server-Protocol \$server_protocol;
        proxy_set_header Server-Name \$server_name;
        proxy_set_header Server-Addr \$server_addr;
        proxy_set_header Server-Port \$server_port;
        proxy_pass http://$websocketServer;
    }

    location ~ /\.ht {
        deny all;
    }

    ssl_certificate     /etc/nginx/ssl/$1.crt;
    ssl_certificate_key /etc/nginx/ssl/$1.key;
}
"

echo "$block" > "/etc/nginx/sites-available/$1"
ln -fs "/etc/nginx/sites-available/$1" "/etc/nginx/sites-enabled/$1"

The main logic here is to create the Nginx virtual host configuration of the Swoole type site. In order to facilitate expansion, we will set the reverse proxy server name by resolving the domain name of the site to set:

# Set Websocket server name
websocketServer=`echo "${1}" | sed "s/^\(.*\)\.test$/\1/g"`

Of course, there are some hard-coded here. For example, the domain name suffix is only supported *.test , and the reverse proxy server IP and port number are also written:

upstream $websocketServer {
    # Connect IP:Port
    server 127.0.0.1:5200 weight=5 max_fails=3 fail_timeout=30s;
    keepalive 16;
}

This is generally sufficient for coping with local development. If you want to make it more scalable, you can refer to the above site configuration analysis and initialization process to introduce new parameters to configure these options.

Configure Swoole Site

Next, we can open Homestead.yaml the configuration file, configuration swoole type of site:

folders:
    ... // Other directory mapping
    - map: ~/Docker/wwwroot/webchat
      to: /home/vagrant/webchat
      
sites:
    ... // other site mapping
    - map: webchat.test
      to: /home/vagrant/webchat/public
    - map: webchats.test
      to: /home/vagrant/webchat/public
      type: swoole
      
databases:
    ... // other databases
    - webchat

Note that here we have created both Nginx virtual host configuration based on PHP-FPM and Swoole as PHP reverse proxy server.

In the host /etc/hosts to add a virtual domain name webchat.test and webchats.test:

192.168.10.10 webchat.test
192.168.10.10 webchats.test

At this point, we have completed all Swoole development environment configurations based on the Homestead virtual machine.

Start Laravel + Swoole Chat Room Project

Next, we can vagrant reload --provision let Swoole type of site configuration to take effect restart the virtual machine, and then modify the webchat project's environmental profile .env is as follows:

APP_URL=http://webchats.test

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=webchat
DB_USERNAME=homestead
DB_PASSWORD=secret

LARAVELS_LISTEN_IP=127.0.0.1
LARAVELS_LISTEN_PORT=5200

Log on to the virtual machine, in the webchat run directory following command to start Swoole HTTP server:

Run functional test scripts to access Home http://webchats.test Success:

In this way, we completed the integration of the Swoole-driven Laravel + Vue chat room project into the Homestead development environment for development testing.