井字游戏多人游戏与 ASP.NET 和信号.创建消息并将其发送到组

Tic-Tac-Toe Multiplayers with ASP.NET and SignalR. Create and send message to a group?

本文关键字:游戏 消息 创建 信号 ASP NET      更新时间:2023-09-26

例如,我有这个链接/Site/Tris/tris.aspx?sessionId=8a657a7b15ee44c39063c8ae45a6ed3b

这是 js 代码:

<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub. 
        var proxy = $.connection.myHub;
        proxy.client.test = function () {
            $('input').hide();//for testing
        };
        // start connetion
        $.connection.hub.start(function () {
            var sessionId = $(document).getUrlParam("sessionId");
            proxy.server.joinGroup(sessionId);
        });
    });
</script>

这是集线器:

 public void JoinGroup(string groupName)
    {
        this.Groups.Add(Context.ConnectionId, groupName);
    }
public void test(string x)
        {
            Clients.Group(x).test();
        }

这是我执行步骤时的 aspx 代码:

 protected void Image_Click(object sender, ImageClickEventArgs e)
    {
        string s = "8a657a7b15ee44c39063c8ae45a6ed3b";
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
        context.Clients.Group(s).test();
    }

当我调用上下文时。Clients.Group(s).test();在 js go 中返回 $.connection.hub.start 并重新加入组并且不调用 test()!为什么?我该怎么办?谢谢

原因是当我单击图像并且 ASPX 中有一个事件时,它会发送一个 POST 请求,因此页面会在之后立即刷新

 proxy.client.test = function () {
            $('input').hide();//for testing
        };`

被称为。我必须仅使用 js 来避免 POST 请求和刷新来完成所有这些操作。