Skip to content

Instantly share code, notes, and snippets.

@Lunchbox4K
Last active August 29, 2015 14:27
Show Gist options
  • Save Lunchbox4K/4003d0e216d4102c6f40 to your computer and use it in GitHub Desktop.
Save Lunchbox4K/4003d0e216d4102c6f40 to your computer and use it in GitHub Desktop.
ASP MVC SignalR Javascrip Chat Room
@{
ViewBag.Title = "Chat";
}
@section scripts {
<script src="Scripts/jquery-1.10.2.min.js"></script>
<!-- SignalR Lib -->
<script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!-- Chat Room Javascript (SignalR)-->
<script src="~/Scripts/mpw-chat.js"></script>
}
<style type="text/css">
#txaChat {
height: 237px;
width: 600px;
}
#txaUsers {
height: 237px;
width: 100px;
}
#txbMessage {
width: 600px;
}
</style>
<h2>Ye Old Chat Room</h2>
<form id="frmChat" runat="server">
Username:&nbsp; <input id="txbUserName" type="text" />
<input id="btnJoin" type="button" value="Join" /><br />
<br />
<textarea id="txaChat" rows="1" readonly="readonly"></textarea>
<textarea id="txaUsers" name="S2" readonly="readonly" rows="2"></textarea>
<br />
<input id="txbMessage" type="text" />
<input id="btnSend" type="button" value="Send"/>
</form>
<hr />
<h3>Source Code</h3>
<h4>Chat Razor View</h4>
<a href="https://gist.github.com/Lunchbox4K/4003d0e216d4102c6f40#file-chat-cshtml">View Source Code</a>
<h4>Chat Razor View SignalR Client Javascript</h4>
<a href="https://gist.github.com/Lunchbox4K/4003d0e216d4102c6f40#file-mpw-chat-js">View Source Code</a>
<h4>SignalR Chat Hub (Server)</h4>
<a href="https://gist.github.com/Lunchbox4K/4003d0e216d4102c6f40#file-chathub-cs">View Source Code</a>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace MPWorks.Hubs
{
/// <summary>
/// SignalR Hub Class for the Chat Room
/// </summary>
public class ChatHub : Hub
{
/// <summary>
/// Connected User Dictionary
/// </summary>
private static readonly Dictionary<string, string> users = new Dictionary<string, string>();
/// <summary>
/// When user disconnects for any reason.
/// </summary>
/// <param name="stopCalled"></param>
/// <returns></returns>
public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
{
string username;
//Try and get username
if (users.TryGetValue(Context.ConnectionId, out username))
{
//Tell others the user left
Clients.All.UserLeft(username);
//Remove user from the server list
users.Remove(Context.ConnectionId);
//ecompiled list, because I was lazy with the client javascript
List<string> userList = new List<string>();
foreach (KeyValuePair<string, string> user in users)
userList.Add(user.Value);
//Send new list to all
Clients.All.UserList(userList, users.Count);
}
return base.OnDisconnected(stopCalled);
}
/// <summary>
/// Handles new user information requesting to join.
/// </summary>
/// <param name="username"></param>
public void UserInformation(string username)
{
//Check for username
bool results = ( !users.ContainsValue(username) );
//Send results back to new user
Clients.Caller.UserInfoResults(results);
if (results)
{
//Add new user to list
users.Add(Context.ConnectionId, username);
//ecompiled list, because I was lazy with the client javascript
List<string> userList = new List<string>();
foreach(KeyValuePair<string,string> user in users)
userList.Add(user.Value);
//Send new list to all
Clients.All.UserList(userList, users.Count);
//Brodcast the new user to all everyone
Clients.All.NewUser(username);
}
}
/// <summary>
/// Handles messsages from connected users.
/// </summary>
/// <param name="message"></param>
public void MessageFromUser(string message)
{
string username;
if (!users.TryGetValue(Context.ConnectionId, out username))
username = "Unknown";
Clients.All.MessageToUsers(username, message);
}
}
}
$(document).ready(function (mpwchat) {
mpwchat.log = mpwchat.log || {}; //Log
//Log write helper function (txaChat ID hard coded in)
mpwchat.log.write = function (message) {
//Create the log message
if (typeof (message) != typeof ("")) message = "[kb] Invalid Log Message Format!";
//Append the new log message
var msg = document.getElementById("txaChat").value;
msg += message + '\n';
document.getElementById("txaChat").value = msg;
}
var conn = $.hubConnection(); //Hub (server) connection private var
var gHub = conn.createHubProxy('chatHub'); //Chat Hub (server) Proxy var
var joinedChat = false; //Joined chat server flag
//Bind Connect Button
$('#btnJoin').click(function () {
//On Connect
if (!joinedChat) {
document.getElementById("txaChat").value = ""; //Reset chat box
mpwchat.log.write("[MPW Chat] Connecting...");
conn.stop();
//Start connection
conn.start().done(function () {
try {
mpwchat.log.write("[MPW Chat] Connected to Chat Server");
//Connect Request
var userName = document.getElementById("txbUserName").value;
if (!userName) {
mpwchat.log.write("[MPW Chat]{Error} Invalid Username");
} else {
mpwchat.log.write("[MPW Chat] Joining as "+userName);
gHub.invoke('userInformation', userName)
.done(function () {
//Request Sent
})
.fail(function (error) {
//Request Failed
mpwchat.log.write("[MPW Chat]{Error} " + error.message);
conn.stop();
joinedChat = false;
});
}
} catch (ex) {
mpwchat.log.write("[MPW Chat]{Error} " + ex.message);
conn.stop();
joinedChat = false;
}
});
//On Disconnect
} else {
conn.stop();
}
});
//Connect Button
$('#btnSend').click(function () {
if (joinedChat)
{
//if (document.getElementById("txbMessage").value.length > 0) {
gHub.invoke('messageFromUser', document.getElementById("txbMessage").value)
.done(function () {
//Request Sent
document.getElementById("txbMessage").value = "";
})
.fail(function (error) {
//Request Failed
mpwchat.log.write("[MPW Chat]{Error} " + error.message);
conn.stop();
joinedChat = false;
});
//}
}
});
//Server message: In response to userInformation
gHub.on('userInfoResults', function (results) {
if (results)
{
mpwchat.log.write("[MPW Chat] Joined Chat");
document.getElementById("btnJoin").value = "Disconnect";
}
else
{
conn.stop();
}
joinedChat = results;
});
//Hub event: Disconnected
conn.disconnected(function () {
mpwchat.log.write("Disconnected");
document.getElementById("txaUsers").value = "";
document.getElementById("btnJoin").value = "Join";
joinedChat = false;
});
//Server message: New user
gHub.on('newUser', function (user) {
document.getElementById("txaChat").value += "User '" + user + "' Joined the chat\n";
});
//Server message: Connected user list
gHub.on('userList', function (users, userCount) {
try {
var userList = document.getElementById("txaUsers");
var list = "";
for(var i = 0; i < userCount; i++)
{
list += users[i];
list += '\n';
}
userList.value = list;
} catch (ex) {
mpwchat.log.write("[MPW Chat]{Error} " + ex.message);
}
});
//Server message: User left
gHub.on('userLeft', function (user) {
try {
document.getElementById("txaChat").value += "User '" + user + "' Disconnected \n";
} catch (ex) {
mpwchat.log.write("[MPW Chat]{Error} " + ex.message);
}
});
//Server message: User message
gHub.on('messageToUsers', function (username, message) {
try{
document.getElementById("txaChat").value += username + ": " + message + '\n';
} catch (ex) {
mpwchat.log.write("[MPW Chat]{Error} " + ex.message);
}
});
} (window.mpwchat = window.mpwchat || {}) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment