Chat Server with Client implemented in C #

Source: Internet
Author: User
Tags foreach bool comments soap mail connect reserved
Client|server Chat server with Client implemented in C #

Submitted by Date of submission
Nanu 01/19/2000


Download:WorkingServer.zip KB
The Main Heart of the program is taken from the sample program of Gopalan Suresh Raj modified as per requirement & PR Esented in front .... Hope it would be helpful for somebody

How to Run the Chat Server and the Client?

(1) Start the Server.exe
(2) Next start Formclient.exe
(3) give you nick name "XYZ" & Click the Connect button ... you'll be connected
To the server & a message would be displaed in the yellow box
(4) Run Formclient.exe again with Start-->run-->formclient.exe & give another
Nick name for trial & error.








The server code:the server Code is implemented in NewServer.cs.

/**
* Article:channels and. NET Remoting
* Copyright (c), Gopalan Suresh Raj. All Rights Reserved.
* File:NewServer.cs
* ... Saurabh for great help to make it lively Your knowledge Rules ....
* ... Mahesh for Loading it on Site .... It Rocks
* ... For Reading it your know better you are:)

* ... The Main Heart of the program is taken from the sample program of Gopalan Suresh Raj
* ... modified as per requirement & presented in front of .... Hope it would be helpful for somebody
*/
Using System;
Using System.IO;
Using System.Collections;
Using System.Runtime.Remoting;
Using System.WinForms;
Using System.Runtime.Remoting.Channels.HTTP;
Namespace Com.icommware.PublishSubscribe {

public class Topic:marshalbyrefobject {


ArrayList userlist = new ArrayList ();
ArrayList textboxlist = new ArrayList ();
ArrayList listboxlist = new ArrayList ();
<summary>
Input:string username (by value) and RichTextBox, ListBox (by refrence)
Output:bool ' true ' if username is unique else ' false '
</summary>
public bool AddUser (string user, ref RichTextBox TextBox1, ref ListBox ListBox1)
{
Check is username was present in the userlist ' ArrayList '
BOOL Test=userlist. Contains (user);
if (test)
{
If present then give the "message" and return ' false '
textbox1.text+= "This Nick has already been taken, try changing your Nick \ n";
return false;
}
else{
User is unique hence add him to the userlist

UserList. ADD (user);
Add the RichTextBox reference to Textboxlist
Textboxlist. ADD (TextBox1);
Add to existing users list
foreach (ListBox lb in listboxlist)
{
Lb. Items.Add (user);
}
Add the ListBox reference to Listboxlist
Listboxlist. ADD (ListBox1);
Send to the client connected
textbox1.text+= "Connected to server ... \ n";
Send message to everyone.
SendMessage (user+ "has joined Chat");
Add all the usernames in the ListBox of the The client
foreach (string users in UserList)
{
LISTBOX1.ITEMS.ADD (users);
}

return true;
}

}

<summary>
Input:string username
It is called the user quits chat
</summary>
public void Removeuser (string user)
{
The check is the user's present in the UserList
try{
if (userlist. Contains (user))
{
Get the position of user in UserList
int i=userlist. IndexOf (user);
Remove user from UserList
UserList. Remove (user);
Remove user ' s RichTextBox reference from Textboxarray
Textboxlist. RemoveAt (i);
Remove user ' s ListBox refrence from Listboxarray
Listboxlist. RemoveAt (i);
Inform all users about user quiting
SendMessage (user+ "has quit Chat");
Emove the user from all users ListBox
foreach (ListBox lb in listboxlist)
{
Lb. Items.remove ((object) user);

}
}
}
catch (Exception ed)
{
Console.WriteLine (ed);
}
}
<summary>
Input:string message
It sends the "message" to "all" users connected to the server
<summary>
public void SendMessage (String message)
{
Write the message on the server console
Console.WriteLine ("Added message: {0}", message);
For each user connected, send the message to them
foreach (RichTextBox rf in textboxlist)
{
Rf. Text+=message+ "\ n";
}

}
}

public class Theserver {

public static void Main () {

int listeningchannel = 1099;
Create a New HTTP Channel that listens on Port Listeningchannel
TCPChannel channel = new TCPChannel (Listeningchannel);
HTTPChannel channel = new HTTPChannel (Listeningchannel);
Register the channel with the runtime
ChannelServices.RegisterChannel (channel);
Expose the Calculator Object from this Server
Remotingservices.registerwellknowntype ("Server"),
"Com.icommware.PublishSubscribe.Topic",
"Topic.soap",
Wellknownobjectmode.singleton);
Keep the Server running until the user presses ENTER
Console.WriteLine ("The Topic Server is up and running on port {0}", Listeningchannel);
Console.WriteLine ("Press ENTER to stop the server ...");
Console.ReadLine ();
}
}
}
That's all ... it ' s all easy if you are willing understand!
Make a printout the IT & open your. NET SDK for better understanding:)



The client code:the client Code reside in NewFormclient.cs.

/**
* Article:channels and. NET Remoting
* Copyright (c), Gopalan Suresh Raj. All Rights Reserved.
* ... Saurabh for great help the IT lively ...:)
* ... Mahesh for Loading it on Site .... It Rocks:)
* ... For Reading it your know better you are:)

* ... The Main Heart of the program is taken from the sample program of Gopalan Suresh Raj
* ... modified as per requirement & presented in front of .... Hope it would be helpful for somebody
*/

Win32Form1.cs
Namespace Win32form1namespace {

Using System;
Using System.Drawing;
Using System.ComponentModel;
Using System.WinForms;
Using System.Runtime.Remoting;
Using System.Runtime.Remoting.Channels.HTTP;
Using Com.icommware.PublishSubscribe;
Using System.Collections;


<summary>
Summary description for Win32form1.
</summary>
public class Win32Form1:System.WinForms.Form {
<summary>
Required by the Win Forms Designer
</summary>
Private System.ComponentModel.Container components;
Private System.WinForms.Button nickname_btn;
Private System.WinForms.TextBox Nickname_txtbox;
Private System.WinForms.Label nickname;
Private System.WinForms.Button Btnlistname;
Private System.WinForms.Button button1;
Private System.WinForms.TextBox TextBox2;
Private System.WinForms.Label Label1;
Private System.WinForms.GroupBox GroupBox1;
Useing RichTextBox insted of TextBox since It supports many more enhancements
Private System.WinForms.RichTextBox TextBox1;
Private System.WinForms.ListBox ListBox1;
Private Topic Topic;
private string Username;
private bool Connected=false;
Private HTTPChannel channel;
Public Win32form1 () {
Required for Win Form Designer support
InitializeComponent ();
Todo:add any constructor the code after InitializeComponent call
}
<summary>
Clean up any being used
</summary>
public override void Dispose () {
Quitclient ();
Base. Dispose ();
Components. Dispose ();
}
<summary>
The main entry point is for the application.
</summary>
public static void Main (string[] args) {
Application.Run (New Win32form1 ());
}

<summary>
Required to Designer support-do not modify
The contents of this method and an editor
</summary>
private void InitializeComponent ()
{
this.components = new System.ComponentModel.Container ();
This.button1 = new System.WinForms.Button ();
This.listbox1 = new System.WinForms.ListBox ();
This.groupbox1 = new System.WinForms.GroupBox ();
This.label1 = new System.WinForms.Label ();
THIS.NICKNAME_BTN = new System.WinForms.Button ();
This.textbox2 = new System.WinForms.TextBox ();
This.nickname = new System.WinForms.Label ();
This.nickname_txtbox = new System.WinForms.TextBox ();
This.btnlistname = new System.WinForms.Button ();
This.textbox1 = new System.WinForms.RichTextBox ();

@design this. trayheight = 0;
@design this. TrayLargeIcon = false;
@design this. Trayautoarrange = true;
Button1. Location = new System.Drawing.Point (136, 64);
Button1. Size = new System.Drawing.Size (72, 24);
Button1. TabIndex = 4;
Button1. Text = "Send";
Button1. Click + + new System.EventHandler (button1_click);

Listbox1.location = new System.Drawing.Point (320, 0);
Listbox1.size = new System.Drawing.Size (152, 329);
Listbox1.tabindex = 0;

Groupbox1.location = new System.Drawing.Point (16, 232);
Groupbox1.tabindex = 0;
Groupbox1.tabstop = false;
Groupbox1.text = "ADD message";
Groupbox1.size = new System.Drawing.Size (240, 104);


Label1. Location = new System.Drawing.Point (16, 32);
Label1. Text = "message";
Label1. Size = new System.Drawing.Size (56, 23);
Label1. TabIndex = 0;

Nickname_btn. Location = new System.Drawing.Point (16, 392);
Nickname_btn. Size = new System.Drawing.Size (224, 24);
Nickname_btn. TabIndex = 2;
Nickname_btn. Text = "Connect";
Nickname_btn. Click + + new System.EventHandler (Nickname_btn_click);

Textbox2.location = new System.Drawing.Point (72, 32);
Textbox2.tabindex = 3;
Textbox2.size = new System.Drawing.Size (160, 20);
Textbox2.click + = new System.EventHandler (button1_click);

Nickname. Location = new System.Drawing.Point (16, 360);
Nickname. Text = "Nick Name";
Nickname. Size = new System.Drawing.Size (72, 16);
Nickname. TabIndex = 0;

Nickname_txtbox. Location = new System.Drawing.Point (88, 360);
Nickname_txtbox. TabIndex = 1;
Nickname_txtbox. Size = new System.Drawing.Size (152, 20);
Nickname_txtbox. Click + + new System.EventHandler (Nickname_btn_click);

Btnlistname.location = new System.Drawing.Point (344, 336);
Btnlistname.size = new System.Drawing.Size (96, 32);
Btnlistname.tabindex = 5;
Btnlistname.text = "Disconnect";
Btnlistname.enabled=false;
Btnlistname.click + = new System.EventHandler (Btnlistname_click);

Textbox1.location = new System.Drawing.Point (24, 8);
Textbox1.multiline = true;
Textbox1.tabindex = 0;
Textbox1.size = new System.Drawing.Size (288, 208);
Textbox1.backcolor = System.Drawing.SystemColors.Info;
This. Text = "Client";
This. AutoScaleBaseSize = new System.Drawing.Size (5, 13);
This. ClientSize = new System.Drawing.Size (496, 425);


GROUPBOX1.CONTROLS.ADD (button1);
GROUPBOX1.CONTROLS.ADD (TEXTBOX2);
GROUPBOX1.CONTROLS.ADD (Label1);
This. Controls.Add (NICKNAME_BTN);
This. Controls.Add (Nickname_txtbox);
This. Controls.Add (nickname);
This. Controls.Add (Btnlistname);
This. Controls.Add (GroupBox1);
This. Controls.Add (TextBox1);
This. Controls.Add (ListBox1);
}
<summary>
Does the cleaning up when client diconnects
</summary>
private void Quitclient ()
{
if (topic!=null)
{
try{
Remove the user from the server
Topic.removeuser (username);
Connected=false;
Set the buttons
Btnlistname.enabled=false;
Nickname_txtbox. Enabled=true;
Nickname_btn. Enabled=true;
ListBox1.Items.Clear ();
Unregister to channel so we can connect some
Channelservices.unregisterchannel (channel);
}
catch (Exception ed)
{
This exception would occur when a 2 clients are running on the same machine and
One try ' s to disconnect.
Since both are using the same port (i.e. ' 0 ') to Conect to server
If you are above we are calling ' Channelservices.unregisterchannel (channel) '
This'll try to close the port ' 0 ' but since another client is
Using this port a exception would occur
Console.WriteLine (ed);
}
}
}

protected void Nickname_btn_click (object sender, System.EventArgs e)
{
try{


Codeing manipulation starts ...
if (!connected)
{
int listeningchannel = 0;
Create and register a channel to communicate to the server
The Client would use the "port passed in as" args to listen for callbacks
Channel = new HTTPChannel (Listeningchannel);
ChannelServices.RegisterChannel (channel);

Create A instance on the remote server and call a method remotely
TOPIC = (topic) Activator.GetObject (typeof (Topic),//type to create
"Http://localhost:1099/Topic.soap"//URI
);

Username = Nickname_txtbox. Text;
Add the user to the server
BOOL check = Topic.adduser (Nickname_txtbox. Text, ref textBox1, ref listBox1);

if (!check)
{
If server rejected user then do cleanup
Connected=false;
Btnlistname.enabled=false;
Nickname_txtbox. Enabled=true;
Nickname_btn. Enabled=true;
Channelservices.unregisterchannel (channel);
Topic=null;
Nickname_txtbox. Text= "";
}
else{
Set up variables and buttons
Connected=true;
Btnlistname.enabled=true;
Nickname_txtbox. Enabled=false;
Nickname_btn. Enabled=false;
This. text= "Client" +username+ "Connected";
}
}


}
catch (Exception ed)
{
MessageBox.Show (This, "Exception occured" +ed. ToString ());
}


}

protected void Btnlistname_click (object sender, System.EventArgs e)
{
Call the Mothod to quit ROM Server
Quitclient ();
}
protected void Button1_Click (object sender, System.EventArgs e)
{
Send the message to everyone
if (textbox2.text!= "") {
Topic.sendmessage (username+ ":" +textbox2.text);
Textbox2.text= "";
}
}

}
}
That's all ... it ' s all easy if you are willing understand!
Make a printout the IT & open your. NET SDK for better understanding:)



If you are have any comments or doubts or find something terrible wrong in the program or comments. Please feel free to e-mail me!


--------------------------------------------------------------------------------

About the Author:everyday I need to satisfy my desire of learning especially in the computer world, and in the same time I ' m really satisfied to share with others what I ' ve learnt. Unfortunately not all programmers today, like me....but a lot of us keep the learning and teaching activity up! Hey don ' t forget to e-mail me nanujogi@yahoo.com.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.