Javascript 如何使用signalR将客户机加入MVC中的组
我到处找,但找不到或不明白如何让客户加入信号员小组。 我对系统用户使用MVC4。 在我向您展示我的代码之前,让我解释一下我要做什么: 我正在编写一个在线Tic TacToe游戏。我的目标是让用户在任何时候打开一个新游戏,一个新的grop(例如:“GameRoom{game id}”将被创建。现在,每当新玩家加入游戏时,他也将加入游戏组。然后,当其中一个玩家移动时,另一个玩家浏览器将刷新以显示新的游戏板。我在主机端编程,但不知道如何在客户端编程。 还有最后一件事——我当前的代码正在使用定时器获取数据。关键是用信号器替换它。 这是我的密码:Javascript 如何使用signalR将客户机加入MVC中的组,javascript,asp.net-mvc,signalr,Javascript,Asp.net Mvc,Signalr,我到处找,但找不到或不明白如何让客户加入信号员小组。 我对系统用户使用MVC4。 在我向您展示我的代码之前,让我解释一下我要做什么: 我正在编写一个在线Tic TacToe游戏。我的目标是让用户在任何时候打开一个新游戏,一个新的grop(例如:“GameRoom{game id}”将被创建。现在,每当新玩家加入游戏时,他也将加入游戏组。然后,当其中一个玩家移动时,另一个玩家浏览器将刷新以显示新的游戏板。我在主机端编程,但不知道如何在客户端编程。 还有最后一件事——我当前的代码正在使用定时器获取数
namespace TicTacToeMVCPart2.Hubs
{
public class GamesHub : Hub
{
public Task JoinGameRoom(string GameRoomName)
{
return Groups.Add(Context.ConnectionId, GameRoomName);
}
public void PlayerClick(string roomName)
{
Clients.OthersInGroup(roomName).OnSquareClicked();
}
}
}
namespace TicTacToeMVCPart2.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
Games = new List<Game>();
}
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public List<Game> Games { get; set; }
public int GamesWon { get; set; }
public int GamesLost { get; set; }
public int GamesDraw { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public DbSet<Game> Games { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
namespace TicTacToeMVCPart2.Models
{
public class Game
{
public Game()
{
}
public Game(string user1Id)
{
User1Id = user1Id;
}
public int GameId { get; set; }
[Required]
public string User1Id { get; set; }
public string User2Id { get; set; }
public string UserIdTurn { get; set; }
public string WinnerId { get; set; }
public bool IsGameOver { get; set; }
public SquareState Square1 { get; set; }
public SquareState Square2 { get; set; }
public SquareState Square3 { get; set; }
public SquareState Square4 { get; set; }
public SquareState Square5 { get; set; }
public SquareState Square6 { get; set; }
public SquareState Square7 { get; set; }
public SquareState Square8 { get; set; }
public SquareState Square9 { get; set; }
}
}
namespace TicTacToeMVCPart2.ViewModels
{
public class GameModel
{
public Game Game { get; set; }
public ApplicationUser User { get; set; }
}
}
namespace TicTacToeMVCPart2.Controllers
{
public class GamesController : Controller
{
ApplicationDbContext context = new ApplicationDbContext();
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
/// <summary>
/// Returns the Logged User Id - defult 0
/// </summary>
public int LoggedUserId
{
get { return Utilites.LoggedUserId(Request); }
}
public ActionResult MyStats()
{
return View("MyStats", UserManager.FindById(User.Identity.GetUserId()));
}
/// <summary>
/// shows all Open Games of other users the logged in user can join
/// </summary>
/// <returns></returns>
public PartialViewResult OpenGames()
{
string userId = User.Identity.GetUserId();
var results = (from game in context.Games
where game.User2Id == null && game.User1Id != userId
select game).ToList();
return PartialView("_allOpenGames", results);
}
/// <summary>
/// returns "_openGameShowScreen" Partial View for a specific game
/// </summary>
/// <param name="gameId"></param>
/// <returns></returns>
public PartialViewResult OpenGameShowScreen(int gameId)
{
var gameResult = GetGameById(gameId);
ApplicationUser user = new ApplicationUser();
if (gameResult != null)
{
user = UserManager.FindById(gameResult.User1Id);
}
GameModel model = new GameModel() { Game = gameResult, User = user };
return PartialView("_openGameShowScreen", model);
}
/// <summary>
/// method that allows users join games and returns the game view or message view for errors
/// </summary>
/// <param name="gameId"></param>
/// <returns></returns>
public ActionResult UserJoinGame(int gameId)
{
ApplicationUser user = UserManager.FindById(User.Identity.GetUserId());
if (user == null)
{
Utilites.CreateMsgCookie(Response, "Error", "Sorry, an unknown error has occurred");
return View("Message");
}
else
{
Game gameResult = GetGameById(gameId);
if (gameResult.User2Id != null) //game already taken
{
Utilites.CreateMsgCookie(Response, "Error", "Game already being taken");
return View("Message");
}
else
{
gameResult.User2Id = user.Id;
Random tmpRNG = new Random();
int tmpInt = tmpRNG.Next(2);
if (tmpInt == 0)
{
gameResult.UserIdTurn = gameResult.User1Id;
}
else
{
gameResult.UserIdTurn = gameResult.User2Id;
}
user.Games.Add(gameResult);
context.SaveChanges();
GameModel model = new GameModel()
{
User = user,
Game = gameResult
};
return View("GameScreen", model);
}
}
}
/// <summary>
/// return "ActiveGamesScreen" view with the results of ActiveGameShowResults(user) as the model
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public ActionResult ActiveGames()
{
ApplicationUser user = UserManager.FindById(User.Identity.GetUserId());
if (user == null)
{
Utilites.CreateMsgCookie(Response, "Error", "Sorry, an unknown error has occurred");
return View("Message");
}
else
{
List<Game> activeGames = ActiveGameShowResults(user);
//ActiveGameShowResults(user);
return View("ActiveGamesScreen", activeGames);
}
}
/// <summary>
/// return all active games of a specific user
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
private List<Game> ActiveGameShowResults(ApplicationUser user)
{
List<Game> results = new List<Game>();
if (user != null)
{
results = context.Games.Where(x => x.IsGameOver == false && x.User2Id != null &&
(x.User1Id == user.Id || x.User2Id == user.Id)).ToList();
}
return results;
}
/// <summary>
/// returns "_activeGameShowScreen" Partial View for a specific game or error in View "Message"
/// </summary>
/// <param name="gameId"></param>
/// <returns></returns>
public ActionResult ActiveGameShowScreen(int gameId)
{
Game game = GetGameById(gameId);
if (game == null)
{
Utilites.CreateMsgCookie(Response, "Error", "Sorry, an unknown error has occurred");
return View("Message");
}
else
{
string userId = User.Identity.GetUserId();
//Get rival user Id
if (game.User1Id == userId)
{
userId = game.User2Id;
}
else
{
userId = game.User1Id;
}
ApplicationUser user = UserManager.FindById(userId);
GameModel model = new GameModel() { Game = game, User = user };
return PartialView("_activeGameShowScreen", model);
}
}
/// <summary>
/// get game from context by gameId , Defult result - null
/// </summary>
/// <param name="gameId"></param>
/// <returns></returns>
private Game GetGameById(int gameId)
{
Game gameResult = (from game in context.Games
where game.GameId == gameId
select game).FirstOrDefault();
return gameResult;
}
/// <summary>
/// method to create new gamrs, returns "GameScreen" View or error by message view
/// </summary>
/// <returns></returns>
public ViewResult CreateNewGame()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user == null)
{
Utilites.CreateMsgCookie(Response, "Error", "Sorry, an unknown error has occurred");
return View("Message");
}
else
{
Game game = new Game();
game.User1Id = user.Id;
user.Games.Add(game);
context.Games.Add(game);
context.SaveChanges();
GameModel model = new GameModel { Game = game, User = user };
return View("GameScreen", model);
}
}
/// <summary>
/// returns GameScreen View by gameId or error by message view
/// </summary>
/// <param name="gameId"></param>
/// <returns></returns>
public ViewResult GoToGameScreen(int gameId)
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user == null)
{
Utilites.CreateMsgCookie(Response, "Error", "Sorry, an unknown error has occurred");
return View("Message");
}
else
{
Game game = GetGameById(gameId);
GameModel model = new GameModel { Game = game, User = user };
return View("GameScreen", model);
}
}
}
namespace TicTacToeMVCPart2.Hubs
{
公共类GamesHub:Hub
{
公共任务JoinGameRoom(字符串GameRoomName)
{
返回Groups.Add(Context.ConnectionId,GameRoomName);
}
public void PlayerClick(字符串roomName)
{
Clients.OthersInGroup(roomName).onsquarecicked();
}
}
}
名称空间TicTacToeMVCPart2.Models
{
//您可以通过向ApplicationUser类添加更多属性来为用户添加配置文件数据,请访问http://go.microsoft.com/fwlink/?LinkID=317594 了解更多。
公共类应用程序用户:IdentityUser
{
公共应用程序用户()
{
游戏=新列表();
}
公共异步任务GenerateUserIdentityAsync(用户管理器)
{
//注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配
var userIdentity=wait manager.CreateIdentityAsync(这是DefaultAuthenticationTypes.ApplicationOkie);
//在此处添加自定义用户声明
返回用户身份;
}
公共列表游戏{get;set;}
public int gameson{get;set;}
public int GamesLost{get;set;}
public int GamesDraw{get;set;}
}
公共类ApplicationDbContext:IdentityDbContext
{
公共应用程序上下文()
:base(“DefaultConnection”,throwifvv1schema:false)
{
}
公共DbSet游戏{get;set;}
公共静态应用程序上下文创建()
{
返回新的ApplicationDbContext();
}
}
}
名称空间TicTacToeMVCPart2.Models
{
公开课游戏
{
公共游戏()
{
}
公共游戏(字符串user1Id)
{
User1Id=User1Id;
}
public int GameId{get;set;}
[必需]
公共字符串User1Id{get;set;}
公共字符串User2Id{get;set;}
公共字符串UserIdTurn{get;set;}
公共字符串WinnerId{get;set;}
公共bool IsGameOver{get;set;}
公共SquareState Square1{get;set;}
公共SquareState Square2{get;set;}
公共SquareState Square3{get;set;}
公共SquareState Square4{get;set;}
公共SquareState Square5{get;set;}
公共SquareState Square6{get;set;}
公共SquareState Square7{get;set;}
公共SquareState Square8{get;set;}
公共SquareState Square9{get;set;}
}
}
命名空间TicTacToeMVCPart2.ViewModels
{
公共类博弈模型
{
公共游戏{get;set;}
公共应用程序用户{get;set;}
}
}
命名空间TicTacToeMVCPart2.Controllers
{
公共类游戏控制器:控制器
{
ApplicationDbContext上下文=新的ApplicationDbContext();
私有应用程序用户管理器\u用户管理器;
公共应用程序管理员用户管理器
{
得到
{
返回_userManager??HttpContext.GetOwinContext().GetUserManager();
}
专用设备
{
_userManager=value;
}
}
///
///返回记录的用户Id-默认值0
///
公共int LoggedUserId
{
获取{return Utilites.LoggedUserId(请求);}
}
公共行动结果MyStats()
{
返回视图(“MyStats”,UserManager.FindById(User.Identity.GetUserId());
}
///
///显示登录用户可以加入的其他用户的所有已打开游戏
///
///
公共PartialViewResult OpenGames()
{
字符串userId=User.Identity.GetUserId();
var results=(来自context.Games中的游戏
其中game.User2Id==null&&game.User1Id!=userId
选择game.ToList();
返回PartialView(“allOpenGames”,结果);
}
///
///返回特定游戏的“\u openGameShowScreen”部分视图
///
///
///
公共PartialViewResult OpenGameShowScreen(int gameId)
{
var gameResult=GetGameById(gameId);
ApplicationUser用户=新的ApplicationUser();
if(gameResult!=null)
{
user=UserManager.FindById(gameResult.User1Id);
}
GameModel model=newGameModel(){Game=gameResult,User=User};
返回PartialView(“openGameShowScreen”,模型);
}
///
///方法,该方法允许用户加入游戏并返回错误的游戏视图或消息视图
///
///
///
public ActionResult UserJoinGame(int gameId)
{
ApplicationUser=UserManager.FindById(user.Identity.GetUserId());
if(user==null)
{
CreateMsgCookie(响应,“错误”,“对不起,发生了未知错误”);
返回视图(“消息”);
}
其他的
{
Game gameResult=GetGameById(gameId);
if(gameResult.User2Id!=null)//游戏已经开始
{
CreateMsgCookie(响应,“错误”,“游戏已被执行”);
namespace TicTacToeMVCPart2.Controllers
{
public class GamesApiController : ApiController
{
ApplicationDbContext context = new ApplicationDbContext();
private ApplicationUserManager _userManager;
public IEnumerable<ApplicationUser> Get()
{
return context.Users;
}
public ApplicationUserManager UserManager
{
get
{
//(System.Web.HttpContext.Current)//lock (System.Web.HttpContext.Current)
//{
return _userManager ?? System.Web.HttpContext.Current.Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
//}
}
private set
{
_userManager = value;
}
}
#region Methods
/// <summary>
/// update the server data by reciving the model and square and returns the new model
/// </summary>
/// <param name="_model"></param>
/// <param name="squareId"></param>
/// <returns></returns>
//square clicked via post
[Route("api/gamesapi/{squareId}")]
public HttpResponseMessage Post([FromBody]GameModel model, int squareId)
{
HttpResponseMessage response;
if (model == null)
{
//Utilites.CreateMsgCookie(Response, "Error", "Sorry, an unknown error has occurred");
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, "model wasn't found");
return response;
}
//GameModel model = JsonConvert.DeserializeObject<GameModel>(_model);
Game game = GetGameById(model.Game.GameId);
if (game == null)
{
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, "game wasn't found");
}
else
{
if (game.UserIdTurn == game.User1Id) //pressing user is user1
{
ChangeSquareState(game, squareId, true);
game.UserIdTurn = game.User2Id;
}
else //game.UserIdTurn == game.User2Id - pressing user is user2
{
ChangeSquareState(game, squareId, false);
game.UserIdTurn = game.User1Id;
}
SquareState[] board = new SquareState[] {game.Square1,game.Square2,game.Square3,game.Square4,
game.Square5,game.Square6,game.Square7,game.Square8,game.Square9};
if (didPlayerWin(board))
{
game.WinnerId = model.User.Id;
UpdateUserGameState(1, game.User1Id);
UpdateUserGameState(2, game.User2Id);
game.IsGameOver = true;
}
else
{
bool isBoardFull = true;
for (int i = 0; i < board.Length; i++)
{
if (board[i] == SquareState.Blank)
{
isBoardFull = false;
break;
}
}
if (isBoardFull)
{
UpdateUserGameState(3, game.User1Id);
UpdateUserGameState(3, game.User2Id);
game.IsGameOver = true;
}
}
context.SaveChanges();
response = Request.CreateResponse(HttpStatusCode.OK, game);
}
return response;
}
/// <summary>
/// When a game is over, recive a gameState and update the user. 1 for a win, 2 for loss, 3 for aa draw
/// </summary>
/// <param name="gameState"></param>
private void UpdateUserGameState(int gameState, string userId)
{
var user = UserManager.FindById(userId);
switch (gameState)
{
case 1:
user.GamesWon++;
break;
case 2:
user.GamesLost++;
break;
case 3:
user.GamesDraw++;
break;
default:
break;
}
UserManager.UpdateAsync(user);
}
[HttpGet]
[Route("api/gamesapi/{gameId}")]
/// <summary>
/// method to bring the latest game's state from the context and send it back in a GameModel
/// </summary>
/// <param name="_model"></param>
/// <returns></returns>
public HttpResponseMessage Get(int gameId)
{
}
/// <summary>
/// method that check if the board have a line(3 squars in a row)
/// of the same element , defult - returns fault
/// </summary>
/// <param name="board"></param>
/// <returns></returns>
private bool didPlayerWin(SquareState[] board)
{
}
/// <summary>
/// change the SquareState of a specific square of the sended game according to the pressing user
/// </summary>
/// <param name="game"></param>
/// <param name="SquareId"></param>
/// <param name="_isUser1"></param>
private void ChangeSquareState(Game game, int SquareId, bool _isUser1)
{
}
/// <summary>
/// get game from context by gameId , Defult result - null
/// </summary>
/// <param name="gameId"></param>
/// <returns></returns>
private Game GetGameById(int gameId)
{
Game gameResult = (from game in context.Games
where game.GameId == gameId
select game).FirstOrDefault();
return gameResult;
}
#endregion
}
public void JoinToGroup(string groupToJoin, string connectionId)
{
var context = GlobalHost.ConnectionManager.GetHubContext<GamesHub>();
context.Groups.Add(connectionId, groupToJoin);
}
public Task JoinGameRoom(string GameRoomName)
{
return Groups.Add(Context.ConnectionId, GameRoomName);
}
var gameHub = $.connection.GameHub;
// You will have to start connection before joining
$.connection.hub.start();
gameHub.server.joinGameRoom("room1");
$.connection.hub.start().done( function () {
gameHub.server.joinGameRoom("room1");
});