【Azure Developer】App Service + PubSub +JS 实现多人版黑客帝国文字流效果图

简介: 【Azure Developer】App Service + PubSub +JS 实现多人版黑客帝国文字流效果图

需要描述

1)实现黑客帝国文字流效果图,JS功能

2)部署在云中,让大家都可以访问,App Service实现

3)大家都能发送消息,并显示在文字流中,PubSub(websocket)实现

 

终极效果显示:

 

执行步骤

1)在 Azure 中创建 App Service 服务,参考官方文档:快速入门:部署 ASP.NET Web 应用

Azure门户中创建App Service的动画演示:

 

2)在 Azure 中创建 PubSub 服务,参考官方文档:快速入门:从 Azure 门户创建 Web PubSub 实例

Azure门户中创建Web PubSub的动画演示:

 

3)使用Visual Studio 2022创建一个.NET 6.0 Web项目,参考PubSub的文档来创建一个服务端来托管 /negotiate API和Web 页面,参考示例:教程:使用子协议在 WebSocket 客户端之间发布和订阅消息

Program.cs文件内容为:

  • string ConnectionString = "<Web PubSub Access Key>" 获取的办法见第二步创建的PubSub服务的Key页面 --> Connection String
using Azure.Messaging.WebPubSub;
using Microsoft.Extensions.Azure;
string ConnectionString = "<Web PubSub Access Key>";
// Add WebPubSub Service 
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAzureClients(builder =>
{
    builder.AddWebPubSubServiceClient(ConnectionString, "stream");
});
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
//实现生产客户端WebSocket SAS URL
app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/negotiate/{userid}", async (string userid, HttpContext context) =>
    {
        var service = context.RequestServices.GetRequiredService<WebPubSubServiceClient>();
        var response = new
        {
            url = service.GetClientAccessUri(userId: userid, roles: new string[] { "webpubsub.sendToGroup.stream", "webpubsub.joinLeaveGroup.stream" }).AbsoluteUri
        };
        await context.Response.WriteAsJsonAsync(response);
    });
});
app.MapGet("/", () => "/index.html");
app.Run();

前端 wwwroot/stream.html 内容为:

<html>
<style>
    html,
    body {
        margin: 0;
        padding: 0;
        background-color: rgb(0, 0, 0);
    }
    #divList {
        width: 98%;
        height: 79%;
        border: solid 1px rgb(0, 15, 0);
        ;
        margin: 0px auto;
        overflow: hidden;
        position: relative;
    }
    .divText {
        position: absolute;
    }
    .divText span {
        display: block;
        font-weight: bold;
        font-family: Courier New;
    }
</style>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<body> <br>
    <h2 style="text-align:center; color:white;">STREAM BOARDCAST (<span id="spanCount">0</span>)</h2>
    <div id="divList">
    </div>
    <h3 style="text-align:left; color:grey;">Send</h3>
    <div style=" margin: 5px 15px;">
        <input id="inputmessage" style="text-align:left; color:green; width: 86%; height: 55px; font-size: 40px;" onsubmit="sendmessage()"><button
            style="text-align:center; color:green; width: 12%; height: 55px;font-size: 40px;" onclick="sendmessage()">Send</button>
    </div>
    <div style="display:none;">
        <h1>Message</h1>
        <div id="output"></div>
        <br>
        <h1>Message</h1>
        <div id="outputmsg"></div>
    </div>
    <script>
        var textarray = ["Hello Mooncake,Welcome to use PubSub", "Who are you? Put your PIN ... "];
        var wsurl = "";
        var wsclient;
        let ackId = 0;
        (async function () {
            let res = await fetch('/negotiate/client_2')
            let data = await res.json();
            wsurl = data.url;
            let ws = new WebSocket(data.url, 'json.webpubsub.azure.v1');
            ws.onopen = () => {
                console.log('connected');
            };
            let output = document.querySelector('#output');
            let outputmsg = document.querySelector('#outputmsg');
            ws.onmessage = event => {
                let d = document.createElement('p');
                d.innerText = event.data;
                output.appendChild(d);
                let message = JSON.parse(event.data);
                if (message.type === 'message' && message.group === 'stream') {
                    let d = document.createElement('span');
                    d.innerText = message.data;
                    textarray.push(message.data);
                    outputmsg.appendChild(d);
                    window.scrollTo(0, document.body.scrollHeight);
                }
            };
            ws.onopen = () => {
                console.log('connected');
                ws.send(JSON.stringify({
                    type: 'joinGroup',
                    group: 'stream',
                    ackId: ++ackId
                }));
                wsclient = ws;
            };
        })();
        function sendmessage() {
            if (wsclient.readyStatue == WebSocket.OPEN) {
                wsclient.send(JSON.stringify(
                    {
                        type: "sendToGroup",
                        group: "stream",
                        data: $('#inputmessage').val(),
                        ackId: ++ackId // ackId is optional, use ackId to make sure this action is executed
                    }
                ));
            }
            else { 
                wsclient = new WebSocket(wsurl, 'json.webpubsub.azure.v1');
                wsclient.onopen = () => {
                    console.log('connected again');
                    wsclient.send(JSON.stringify({
                        type: "sendToGroup",
                        group: "stream",
                        data: $('#inputmessage').val(),
                        ackId: ++ackId
                    }));
 
                };
            }
            $('#inputmessage').focus();
        }
        function rand(min, max) {
            return min + Math.round(Math.random() * (max - min));
        }
        function add(message) {
            var maxwdth = $('#divList').width();
            var x = rand(0, maxwdth);
            var html = '<div class="divText" style="left:' + x + 'px; bottom:500px;">';
            var color = [];
            for (var i = 1; i < message.length; i++) {
                var f = i.toString(16);
                color.push('0' + f + '0');
            }
            var fontSize = rand(20, 36);
            for (var i = 1; i <= message.length; i++) {
                var c = message[i - 1];
                html += '<span class="s' + i + '" style="color:#' + color[i - 1] + '; font-size:' + fontSize + 'px; text-shadow:0px 0px 10px #' + color[i - 1] + ';">' + c + '</span>';
            }
            html += '</div>';
            $('#divList').append(html);
        }
        function run() {
            var x = rand(0, 100);
            if (x < 100) {
                var lgh = textarray.length;
                if (textarray.length > x) add(textarray[x]);
                else
                    add(textarray[x % lgh]);
            }
            $('#spanCount').html($('.divText').size());
            $('.divText').each(function () {
                var y = $(this).css('bottom');
                y = parseInt(y);
                y -= $(this).find('span').eq(0).height();
                $(this).css('bottom', '' + y + 'px');
                if (y + $(this).height() <= 0) {
                    $(this).remove();
                    return;
                }
            });
            window.setTimeout(run, 200);
        }
        run();
    </script>
</body>
</html>

项目结构示意图:

 

项目创建完成后,可以在本机进行调试。正常运行后即可发布到Azure App Service上。因代码简单并且可读性强,可自行理解。

 

4)通过VS 2022发布到App Service中

VS 2022 通过Publish Profile 发布站点演示动画:

发布版本操作完成。

 

附录一:本地黑客帝国文字流效果,可自行输入即修改内容版

复制内容,直接保存在本地文件中,文件命名为 localstream.html后使用浏览器打开即可

<html>
<style>
    html,
    body {
        margin: 0;
        padding: 0;
        background-color: rgb(0, 0, 0);
    }
    #divList {
        width: 98%;
        height: 79%;
        border: solid 1px rgb(0, 15, 0);
        ;
        margin: 0px auto;
        overflow: hidden;
        position: relative;
    }
    .divText {
        position: absolute;
    }
    .divText span {
        display: block;
        font-weight: bold;
        font-family: Courier New;
    }
</style>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<body> <br>
    <h2 style="text-align:center; color:white;">STREAM BOARDCAST (<span id="spanCount">0</span>)</h2>
    <div id="divList">
    </div>
    <h3 style="text-align:left; color:grey;">Send</h3>
    <div style=" margin: 5px 15px;">
        <input id="inputmessage" style="text-align:left; color:green; width: 86%; height: 55px; font-size: 40px;" onsubmit="sendmessage()"><button
            style="text-align:center; color:green; width: 12%; height: 55px;font-size: 40px;" onclick="sendmessage()">Send</button>
    </div>
    <div style="display:none;">
        <h1>Message</h1>
        <div id="output"></div>
        <br>
        <h1>Message</h1>
        <div id="outputmsg"></div>
    </div>
    <script>
        var textarray = ["Hello Mooncake,Welcome to use PubSub", "Who are you? Put your PIN ... "];
        function sendmessage() {
            textarray.push($('#inputmessage').val());
            $('#inputmessage').focus();
        }
        function rand(min, max) {
            return min + Math.round(Math.random() * (max - min));
        }
        function add(message) {
            var maxwdth = $('#divList').width();
            var x = rand(0, maxwdth);
            var html = '<div class="divText" style="left:' + x + 'px; bottom:500px;">';
            var color = [];
            for (var i = 1; i < message.length; i++) {
                var f = i.toString(16);
                color.push('0' + f + '0');
            }
            var fontSize = rand(20, 36);
            for (var i = 1; i <= message.length; i++) {
                var c = message[i - 1];
                html += '<span class="s' + i + '" style="color:#' + color[i - 1] + '; font-size:' + fontSize + 'px; text-shadow:0px 0px 10px #' + color[i - 1] + ';">' + c + '</span>';
            }
            html += '</div>';
            $('#divList').append(html);
        }
        function run() {
            var x = rand(0, 100);
            if (x < 100) {
                var lgh = textarray.length;
                if (textarray.length > x) add(textarray[x]);
                else
                    add(textarray[x % lgh]);
            }
            $('#spanCount').html($('.divText').size());
            $('.divText').each(function () {
                var y = $(this).css('bottom');
                y = parseInt(y);
                y -= $(this).find('span').eq(0).height();
                $(this).css('bottom', '' + y + 'px');
                if (y + $(this).height() <= 0) {
                    $(this).remove();
                    return;
                }
            });
            window.setTimeout(run, 200);
        }
        run();
    </script>
</body>
</html>

PS: 与PubSub版本相比,只是移除了WebSocket的相关代码

运行效果

 

 

参考资料

JS 黑客帝国文字下落效果: https://www.cnblogs.com/zjfree/p/3833592.html

教程:使用子协议在 WebSocket 客户端之间发布和订阅消息:https://docs.microsoft.com/zh-cn/azure/azure-web-pubsub/tutorial-subprotocol?tabs=csharp#using-a-subprotocol

快速入门:部署 ASP.NET Web 应用:https://docs.azure.cn/zh-cn/app-service/quickstart-dotnetcore?tabs=net60&pivots=development-environment-vs

 

相关文章
|
4天前
|
数据采集 JavaScript Android开发
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
29 7
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
5天前
|
JavaScript API
【Azure Function】Function App门户上的Test/Run返回错误:Failed to fetch
Running your function in portal requires the app to explicitly accept requests from https://portal.azure.cn. This is known as cross-origin resource sharing (CORS).Configure CORS to add https://portal.azure.cn to allowed origins.
|
15天前
|
应用服务中间件 Linux nginx
【Azure App Service】基于Linux创建的App Service是否可以主动升级内置的Nginx版本呢?
基于Linux创建的App Service是否可以主动升级内置的Nginx版本呢?Web App Linux 默认使用的 Nginx 版本是由平台预定义的,无法更改这个版本。
126 77
|
19天前
|
C#
【Azure Function】Function App出现System.IO.FileNotFoundException异常
Exception while executing function: xxxxxxx,The type initializer for 'xxxxxx.Storage.Adls2.StoreDataLakeGen2Reading' threw an exception. Could not load file or assembly 'Microsoft.Extensions.Configuration, Version=9.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the
114 64
|
22天前
|
监控 关系型数据库 MySQL
|
1月前
|
Windows
【Azure App Service】对App Service中CPU指标数据中系统占用部分(System CPU)的解释
在Azure App Service中,CPU占比可在App Service Plan级别查看整个实例的资源使用情况。具体应用中仅能查看CPU时间,需通过公式【CPU Time / (CPU核数 * 60)】估算占比。CPU百分比适用于可横向扩展的计划(Basic、Standard、Premium),而CPU时间适用于Free或Shared计划。然而,CPU Percentage包含所有应用及系统占用的CPU,高CPU指标可能由系统而非应用请求引起。详细分析每个进程的CPU占用需抓取Windows Performance Trace数据。
94 40
|
2月前
|
API
【Azure Logic App】使用Logic App来定制Monitor Alert邮件内容遇见无法获取SearchResults的情况
Log search alert rules from API version 2020-05-01 use this payload type, which only supports common schema. Search results aren't embedded in the log search alerts payload when you use this version.
54 10
|
3月前
|
缓存 容器 Perl
【Azure Container App】Container Apps 设置延迟删除 (terminationGracePeriodSeconds) 的解释
terminationGracePeriodSeconds : 这个参数的定义是从pod收到terminated signal到最终shutdown的最大时间,这段时间是给pod中的application 缓冲时间用来处理链接关闭,应用清理缓存的;并不是从idel 到 pod被shutdown之间的时间;且是最大时间,意味着如果application 已经gracefully shutdown,POD可能被提前terminated.
|
3月前
|
Java 开发工具 Windows
【Azure App Service】在App Service中调用Stroage SDK上传文件时遇见 System.OutOfMemoryException
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

热门文章

最新文章

  • 1
    MNN-LLM App:在手机上离线运行大模型,阿里巴巴开源基于 MNN-LLM 框架开发的手机 AI 助手应用
  • 2
    【11】flutter进行了聊天页面的开发-增加了即时通讯聊天的整体页面和组件-切换-朋友-陌生人-vip开通详细页面-即时通讯sdk准备-直播sdk准备-即时通讯有无UI集成的区别介绍-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
  • 3
    原生鸿蒙版小艺APP接入DeepSeek-R1,为HarmonyOS应用开发注入新活力
  • 4
    【Azure App Service】基于Linux创建的App Service是否可以主动升级内置的Nginx版本呢?
  • 5
    【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
  • 6
    【05】flutter完成注册页面完善样式bug-增加自定义可复用组件widgets-严格规划文件和目录结构-规范入口文件-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草央千澈
  • 7
    【Azure Function】Function App出现System.IO.FileNotFoundException异常
  • 8
    【Azure Logic App】使用MySQL 新增行触发器遇见错误 :“Unknown column 'created_at' in 'order clause'”
  • 9
    阿里云APP备案流程图以及备案所需材料整理,跟着教程一步步操作
  • 10
    【04】flutter补打包流程的签名过程-APP安卓调试配置-结构化项目目录-完善注册相关页面-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程
  • 1
    当面试官再问我JS闭包时,我能答出来的都在这里了。
    49
  • 2
    【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
    29
  • 3
    Node.js 中实现多任务下载的并发控制策略
    34
  • 4
    【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
    26
  • 5
    【JavaScript】深入理解 let、var 和 const
    49
  • 6
    【04】Java+若依+vue.js技术栈实现钱包积分管理系统项目-若依框架二次开发准备工作-以及建立初步后端目录菜单列-优雅草卓伊凡商业项目实战
    47
  • 7
    【03】Java+若依+vue.js技术栈实现钱包积分管理系统项目-若依框架搭建-服务端-后台管理-整体搭建-优雅草卓伊凡商业项目实战
    57
  • 8
    【02】Java+若依+vue.js技术栈实现钱包积分管理系统项目-商业级电玩城积分系统商业项目实战-ui设计图figmaUI设计准备-figma汉化插件-mysql数据库设计-优雅草卓伊凡商业项目实战
    57
  • 9
    如何通过pm2以cluster模式多进程部署next.js(包括docker下的部署)
    72
  • 10
    【01】Java+若依+vue.js技术栈实现钱包积分管理系统项目-商业级电玩城积分系统商业项目实战-需求改为思维导图-设计数据库-确定基础架构和设计-优雅草卓伊凡商业项目实战
    57