MomentPHP 畅通异步WebSocket了!

in 前后端开发 with 0 comment

MomentPHP就像一个busybox,可以在极小损耗的情况下实现很多功能
今天,万众瞩目的异步WebSocket出现了!

2024-05-02T01:40:39.png

50行代码,其中只要5行就可以启用WebSocket交互了!
这样,下次我们搭配php-pty就可以实现远程终端...嘿嘿嘿

<?php
use MomentCore\HttpHandle;
use MomentCore\WebSocket;

return function(HttpHandle $handle){ 
    try{
        $handle -> ws() -> then(function(WebSocket $ws){
            $ws -> onMessage(function(string $msg) use ($ws){
                $ws -> send($msg);
            }); 
        });
    }catch(\Throwable $e){}
?>
<!DOCTYPE html>
    <html lang="zh">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Web Terminal</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/xterm/5.5.0/xterm.min.css">
    </head>
    <body>
        <div id="terminal"></div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/xterm/5.5.0/xterm.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/@xterm/addon-fit@0.10.0/lib/addon-fit.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/@xterm/addon-webgl@0.18.0/lib/addon-webgl.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/@xterm/addon-attach@0.11.0/lib/addon-attach.min.js"></script>
        <script>
            var term = new Terminal({
                rendererType: "webgl",
                convertEol: true,
                scrollback: 100,
                disableStdin: false,
                cursorBlink: true
            });
            var socket = new WebSocket(`ws://${location.host}${location.pathname}`);
            var attachAddon = new AttachAddon.AttachAddon(socket);
            var fitAddon = new FitAddon.FitAddon();
            term.loadAddon(fitAddon);
            term.loadAddon(attachAddon);
            term.loadAddon(new WebglAddon.WebglAddon());

            term.open(document.getElementById('terminal'));

            window.addEventListener('resize', function(){
                term.fit();
            });
        </script>
    </body>
</html>
<?php } ?>

后记

WebSocket比较难(难在WebSocket的一堆信息头),好在我之前就写好了好用的readreadline,否则像workerman那样还要判断 数据是否足够 要死的!

Responses