程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> Chat Server with Client implemented in C#

Chat Server with Client implemented in C#

編輯:關於C語言

Submitted By Date of Submission
Nanu  01/19/2000

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

How to Run the Chat Server and the ClIEnt?

(1) First start the server.exe
(2) Next start formclIEnt.exe
(3) Give you nick name "xyz" & click the connect button .... you will be connected
to the server & a message will 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) 2000, Gopalan Suresh Raj. All Rights Reserved.
* File: NewServer.cs
* ... Thanks Saurabh for great help to make it lively Your Knowledge Rules ....
* ... Thanks Mahesh for Loading it on Site .... It Rocks
* ... Thanks to You for Reading it You know better who 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 you.... 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 is present in the userlist 'ArrayList'
bool test=userlist.Contains(user) ;
if(test)
{
//if present then Give the message to use 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 message only 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 clIEnt
foreach(string users in userlist)
{
listBox1.Items.Add(users) ;
}
  
return true ;
}
  
}
  
///<summary>
/// Input: string username
/// It is called when the user quits chat
///</summary>
public void removeUser(string user)
{
//check is the user is 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 of 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) 2000, Gopalan Suresh Raj. All Rights Reserved.
* ... Thanks Saurabh for great help to make it lively .... thanks :)
* ... Thanks Mahesh for Loading it on Site .... It Rocks :)
* ... Thanks to You for Reading it You know better who 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 you.... 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 code after InitializeComponent call
}
/// <summary>
/// Clean up any resources being used
/// </summary>
public override void Dispose() {
quitclIEnt() ;
base.Dispose();
components.Dispose();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
public static void Main(string[] args) {
Application.Run(new Win32Form1());
}
  
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with 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 other place
ChannelServices.UnregisterChannel(channel) ;
}
catch(Exception ed)
{
//this exception will 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 see above we are calling 'ChannelServices.UnregisterChannel(channel)'
//this will try to close the port '0' but since another clIEnt is
//using this port a exception will occur
Console.WriteLine(ed) ;
}
}
}
  
protected void nickname_btn_Click(object sender, System.EventArgs e)
{
try{
  
  
// codeing manipulation starts here ...
if(!connected)
{
int listeningChannel = 0;
// Create and register a channel to communicate to the server
// The ClIEnt will use the port passed in as args to listen for callbacks
channel = new HTTPChannel (listeningChannel);
ChannelServices.RegisterChannel (channel);
  
// Create an 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 of it & open your .Net sdk for better understanding :)



If you have any comments or doubts or find something terrible wrong in 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 think like me....but a lot of us keep  the learning and teaching activity up! Hey don't forget to e-mail me [email protected].
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved