一步一步学习SignalR进行实时通信_8_案例2

一步一步学习SignalR进行实时通信_8_案例2

标签(空格分隔): SignalR


前言

这讲分析一个案例,在一个画板上画画实时在其他客户端上显示。

配置Hub

在Startup中进行配置:

public void Configuration(IAppBuilder app)
{
    app.MapSignalR();
}

建立DrawingHub

public class Drawing : Hub
{
    private const int BoardWidth = 300, BoardHeight = 300;
    private static int[,] _buffer = new int[BoardWidth, BoardHeight];
    public Task BroadcastPoint(int x, int y)
    {
        if (x < 0) x = 0;
        if (x >= BoardWidth) x = BoardWidth - 1;
        if (y < 0) y = 0;
        if (y >= BoardHeight) y = BoardHeight - 1;
        int color = 0;
        int.TryParse(Clients.Caller.color, out color);
        _buffer[x, y] = color;
        return Clients.Others.DrawPoint(x, y, Clients.Caller.color);
    }
    public Task BroadcastClear()
    {
        _buffer = new int[BoardWidth, BoardHeight];
        return Clients.Others.Clear();
    }
    public override Task OnConnected()
    {
        return Clients.Caller.Update(_buffer);
    }
}

用一个二位数组来缓存画板,一共就三个方法

  1. 当客户端连接时调用Update()方法刷新整个画板
  2. BroadcastClear()是点击清除按钮时讲整个画板擦出
  3. 最后一个就是画画方法,客户端按下鼠标画画时,调用该方法进行绘制。

页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Drawing board</title>
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.0.0.min.js"></script>
    <script src="/signalr/js"></script>
    <script src="Scripts/DrawingBoard.js"></script>
    <style>
        div {
            margin: 3px;
        }
        canvas {
            border: 2px solid #808080;
            cursor: default;
        }
    </style>
</head>
<body>
    <div>
        <div>
            <label for="color">Color: </label>
            <select id="color">
            </select>
        </div>
        <canvas id="canvas" width="300" height="300"></canvas>
        <div>
            <button id="clear">Clear canvas</button>
        </div>
    </div>
</body>
</html>

页面非常简单,一个选择颜色的下拉框,一个画板,和一个清除按钮。

javascript

$(function () {
//初始化
    var colors = ["black", "red", "green", "blue", "yellow", "magenta", "white"];
    var canvas = $("#canvas");
    var colorElement = $("#color");
    for (var i = 0; i < colors.length; i++) {
        colorElement.append(
            "<option value='" + (i + 1) + "'>" + colors[i] + "</li>"
        );
    }
    //画板鼠标事件
    var buttonPressed = false;
    canvas.mousedown(function () {
            buttonPressed = true;
        })
        .mouseup(function () {
            buttonPressed = false;
        })
        .mousemove(function (e) {
            if (buttonPressed) {
                setPoint(e.offsetX, e.offsetY, colorElement.val());
            }
        });
    var ctx = canvas[0].getContext("2d");
    //画画
    function setPoint(x, y, color) {
        ctx.fillStyle = colors[color - 1];
        ctx.beginPath();
        ctx.arc(x, y, 2, 0, Math.PI * 2);
        ctx.fill();
    }
    //清除
    function clearPoints() {
        ctx.clearRect(0, 0, canvas.width(), canvas.height());
    }
    $("#clear").click(function () {
        clearPoints();
    });
    //signalR
    var hub = $.connection.drawingBoard;
    //缓存颜色
    hub.state.color = colorElement.val(); 
    var connected = false;
    //改变颜色
    colorElement.change(function () {
        hub.state.color = $(this).val();
    });
    //当连接时且鼠标按下时调用
    canvas.mousemove(function (e) {
        if (buttonPressed && connected) {
            hub.server.broadcastPoint(
                Math.round(e.offsetX), Math.round(e.offsetY)
            );
        }
    });
    $("#clear").click(function () {
        if (connected) {
            hub.server.broadcastClear();
        }
    });
    hub.client.clear = function () {
        clearPoints();
    };
    hub.client.drawPoint = function (x, y, color) {
        setPoint(x, y, color);
    };
    //更新整个画板
    hub.client.update = function (points) {
        if (!points) return;
        for (var x = 0; x < 300; x++) {
            for (var y = 0; y < 300; y++) {
                if (points[x][y]) {
                    setPoint(x, y, points[x][y]);
                }
            }
        }
    };
    $.connection.hub.start()
        .done(function () {
            connected = true;
        });
});

实现效果

结束语

简单的讲了一个小案例。
源码下载
本文发布至作业部落

参考文献

SignalR Programming in Microsoft ASP.NET pdf 下载

posted @ 2015-11-20 00:12  杰哥很忙  阅读(1465)  评论(0编辑  收藏  举报