在我的聊天应用程序项目中,每当有新用户连接到服务器时,我都会尝试向所有用户广播用户名。并在用户离开服务器时删除用户名。以下是我通过教程尝试过的代码。(请检查file.js
未显示所需输出的文件)
Chat.cs ( Working ) --> 实现 SignalR 的 "Hub" 类
public class Chat : Hub
{
/* showing only related content */
static ConcurrentDictionary<string, User> _users = new ConcurrentDictionary<string, User>();
public override Task OnDisconnected()
{
var user = _users[Context.ConnectionId]; //user as ConnectionId
User removedUser; //new class object
_users.TryRemove(Context.ConnectionId, out removedUser);
return Clients.All.leave(user, DateTime.Now.ToString()); //dynamic expression
}
public void Joined()
{
User user = new User(Context.ConnectionId, Clients.Caller.username);
_users.TryAdd(user.ConnectionID, user);
Clients.All.joins(user.ConnectionID, user.Name, DateTime.Now); //dynamic expression
}
}
User.cs(工作)
public class User
{
public User(string ConnID, string Username)
{
Name = Username;
ConnectionID = ConnID;
}
public string Name { get; set; }
public string ConnectionID { get; set; }
}
file.js(不工作)
var chatUsername = window.prompt("Enter Username:", ""); //username
var chat = $.connection.chat; //connection
//
chat.client.joins = function (ConnectionId, name, Date) {
ConnectionId = 1; /* given value to just test */
name = chatUsername;
};
chat.client.leave = function (user, date) {
user = ""; //making the string empty so that the disconnected user value will be lost.
};
//Here is the connection which calls the "Joined" function of the server (Chat.cs)
我应该在file.js
函数(加入和离开)中写什么,这样我才能得到我上面提到的预期结果。在问这里之前,我已经浏览了这个网站,它正在做同样的事情,但包括我不想包括的其他 javascript 文件(knockout.js 和 json)。(因为我是 jquery 的新手)。