SignalR Chat Server and Chat Client Application
Today , I will tell you how to create chat client and chat server.
Create a Chat Server
Start an mvc project in the first step.
We build the following packages in the project(Tools ->NuGet Package Manager -> Package Manager Console)
2 |
Install-Package Microsoft.AspNet.SignalR -Version 2.2.3 |
2 |
Install-Package Microsoft.Owin.Cors -Version 4.0.0 |
Later, we create a OWIN Startup class
- File:Startup.cs
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Startup { public void Configuration(IAppBuilder app) { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888 app.UseCors(CorsOptions.AllowAll); app.Map("/signalr", map => { var hubConfigration = new HubConfiguration { EnableJSONP = true, EnableJavaScriptProxies = false }; map.RunSignalR(hubConfigration); }); } } |
Create a SignaR Hub Class
- I’ve written explanations of the necessary places in the code, it’s easy to understand. Leave a message in the place you do not know.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
public class ChatHub : Hub { public static List<Users> users = new List<Users>(); public void Hello() { Clients.All.hello(); } public void SendMessage(string message,string send_connectionID) //I have defined 2 parameters. These are the parameters to be sent here from the client software { var sender_connectionID = Context.ConnectionId; Users user = users.Where(x => x.connectionID.Equals(sender_connectionID)).FirstOrDefault(); if(user!=null) { Clients.Client(send_connectionID).SendMessage(message, user.username); } } public override Task OnConnected() { var connectionID = Context.ConnectionId; string userName = Context.QueryString["username"]; if(string.IsNullOrEmpty(userName)) { userName = Context.Headers["username"]; } Users user = new Users() { username = userName, connectionID = connectionID }; users.Add(user); //add the connection user to the list string json = JsonConvert.SerializeObject(users); //send to client Clients.All.getUserList(json); return base.OnConnected(); } public override Task OnDisconnected(bool stopCalled) { var connectionID = Context.ConnectionId; Users user = users.Where(x => x.connectionID.Equals(connectionID)).FirstOrDefault(); if(user!=null) { users.Remove(user); //in the case of connection termination we removed the user from the list string json = JsonConvert.SerializeObject(users); //send to client Clients.All.getUserList(json); } return base.OnDisconnected(stopCalled); } public class Users { public string username { get; set; } public string connectionID { get; set; } } } |
The purpose of using Query String and header is also to be understood in Android and iOS applications.
Create a Chat Client
You setup command line.Do not install if you do not want to use Metroframework.
Create a new C# form application.(I will do this in the android later).
You can create projects in the same solution as below
Then we design the form screen. I designed it this way. Design it as you like.
In the code I put the necessary description lines clearly.If you do not want to use MetroFramework, change Form1: MetroForm to Form1: Form
- File:Form1.cs
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
public partial class Form1 : MetroForm { HubConnection connection; // Connection defination IHubProxy chat; // chat proxy defination List<Users> users = null; // user list Users sender_message = null; // sender message in user public Form1() { InitializeComponent(); } bool connect(string userName) { connection = new HubConnection("http://localhost:12968/signalr"); connection.Headers.Add("username", userName); chat = connection.CreateHubProxy("ChatHub"); try { chat.On<string>("getUserList", (message) => { // getUserList is ChatHub function var json_serialize = new JavaScriptSerializer(); users = json_serialize.Deserialize<List<Users>>(message); string[] user_names = users.Select(x => x.username).ToArray(); this.BeginInvoke(new Action(()=>{ listBox1.Items.Clear(); listBox1.Items.AddRange(user_names);//User List in ListBox })); }); chat.On<string, string>("sendMessage", (message, user) => //sendMessage is ChatHub function { this.BeginInvoke(new Action(() => { richTextBox1.Text += user + ":" + message + "\n"; // writing username and message on richTextBox1 })); }); connection.Start().Wait(); return true; } catch (Exception e) { return false; } } private void button1_Click(object sender, EventArgs e) { if (connect(user.Text.Trim())) { button1.Enabled = false; // Server Connection button2.Enabled = true; } else { MessageBox.Show("Error"); } } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (listBox1.SelectedIndex != -1) { sender_message = users[listBox1.SelectedIndex]; //to send a message to the selected person button3.Enabled = true; } else { button3.Enabled = false; sender_message = null; } } private void button2_Click(object sender, EventArgs e) { connection.Stop(); // Connection Stop button1.Enabled = true; button2.Enabled = false; listBox1.Items.Clear(); sender_message = null; button3.Enabled = false; } private void button3_Click(object sender, EventArgs e) { if(!textbox1.Text.Trim().Equals("")&& sender_message != null) { chat.Invoke("SendMessage", textbox1.Text.Trim(), sender_message.connectionID); //Send message to user textbox1.Text = ""; listBox1.SelectedIndex = -1; } } public class Users //User Model { public string username { get; set; } public string connectionID { get; set; } } } |
Code part complete.
Great post friend!!
You saved my time ..
Thank you
Thank You !
Your post was helpful to me.
You happen to have the javascript version of the C # client
You’re welcome 🙂
hi all
the firsts thanks you very much
now i want to connect signalr to server host, but when i change link “http://…” so signalr not connect
thank u
Are you sure you have the corresponding url correctly while creating the connection object?