1.创建服务端监听
public class TrackerConnection : PersistentConnection
{
protected override Task OnReceived(IRequest request, string connectionId, string data)
{
return Connection.Broadcast(data);
}
}
2.添加路由注册
//注册服务器端相应路由
app.MapSignalR<TrackerConnection>("/tracker");
3.客户端JS监听
<script type="text/javascript">
//SignalR 客户端
var connection = $.connection('/tracker');
connection.logging = true;
//连接建立
connection.start(function () {
startTracking();
});
//客户端接收消息
connection.received(function (data) {
data = JSON.parse(data);
var elemID = 'id' + data.id;
var elem = createElementIfNotExists(elemID);
$(elem).css({
left: data.x,
top:data.y
}).text(data.id);
});
function startTracking() {
$(document.body).mousemove(function (e) {
//发送json 对象
//从当前上下文中获取连接对象
var data = { x: e.pageX, y: e.pageY, id: connection.id };
connection.send(data);
});
}
/* Helper functions */
function createElementIfNotExists(id) {
var element = $("#" + id);
if (element.length == 0) {
element = $("<span class='client' " +
"id='" + id + "'></span>");
var color = getRandomColor();
element.css({
backgroundColor: getRgb(color),
color: getInverseRgb(color)
});
$("body").append(element).show();
}
return element;
}
function getRgb(rgb) {
return "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
}
function getInverseRgb(rgb) {
return "rgb(" + (255 - rgb.r) + "," +
(255 - rgb.g) + "," + (255 - rgb.b) + ")";
}
function getRandomColor() {
return {
r: Math.round(Math.random() * 256),
g: Math.round(Math.random() * 256),
b: Math.round(Math.random() * 256),
};
}
</script>