Global Text Chat Room Application using C#.NET Remoting Technology(转载)
2010-06-07 23:04
513 查看
Download source - 70.56 KB
Visit my personal technical blog on Socket Programming in C#
Now run the client application. Here you will first get a Window which will ask your name and server address, port, etc. If you try with the same machine, then the given address is ok. But if it is a different address, then you need to update ‘
Now the chat room window will appear. Here there are three sections. The left and large one is the chat history, the right list is for online users, the bottom area for entering your text and send button for sending message to the server.
Base Remoting class: This is like a bridge to communicate between Client and Server. It exists in a DLL file which shares Server and Client program.
Server class: It is a server to serve Client requests. Every client connects to Server to communicate with each other. This program holds a Remoting class’s DLL.
Client class: This is the client part of Remoting architecture. This also holds a copy of Remoting base DLL. It connects to Server and via server communicates to other client.
This is very simple idea of Remoting architecture. If you want to learn about this technology, then you may read from the MSDN site.
As Remoting architecture here has a base class (class library) and after compiling, produces a DLL file with name ‘RemoteBase.dll’. This DLL has about six methods like:
The next one is the Server, this is a Windows Form (WinForms) application. This application uses ‘RemoteBase.dll’ as its reference file for library. Server registers a TCP channel with a port number. You may choose any port number from 1025 to 65k. And it registers for well known type of
When you run the server, you will see a window as the attached screen shot and need to press button ‘Start’ to start the server and check server status as ‘Running’. To stop the server, you need to press on ‘Stop’ button.
The last one is the Client part, it is also a Windows form (
There also is a server address like ‘tcp://localhost:8080/HelloWorld’ here ‘localhost’ is the server address and 8080 is the port number. Server address needs to tell where your server is running. I am using server and client in the same machine so server address is ‘localhost’, you may give any IP address here. Port number can also be changed but server opening port number and client requesting port number should be the same. You cannot change the remaining things in address, otherwise this chat application will not work.
Chat room window has four sections, the largest one to see all chat messages and below that to type chat message, and send button to send message to server. Just above is the list to display all online users.
When you put your name, then client application creates a remote base class’s object and connects to server by registering TCP channel. Then it connects to Chat Room and seeks the latest message number. After that, the main Chat Room window opens. From that window, it seeks the latest available message in the server by a timer. To get message from server, it invokes ‘
Collapse
Copy Code
Here a
On the other hand, when user presses ‘Stop’ server, then unregister the channel and stop the server. The code is shown below:
Collapse
Copy Code
Collapse
Copy Code
Here from the user, the client application takes a name and checks with the server if the name is available or not. If the name is available, then user gets the ‘
If user name is already taken by another user, then the application asks the user for a different name.
On the server side to join a user in chat server “
Collapse
Copy Code
Here the user can successfully log in to the server, then his name is added in a user collection, ‘
Collapse
Copy Code
Here client application invokes the “
Collapse
Copy Code
Wow! This is very small code. Actually this is adding the users’ message to another collection. I have used for this collection of
See here there is one counter ‘key’ which is incrementing by one. This is the counter which is maintaining the chat message number. It will help us to get the chat message from server.
Collapse
Copy Code
Here client invokes “
Collapse
Copy Code
The server just takes the key as last-key of user’s message and uses it in Chat message collection to fetch the next chat message, after that the message returns to the client.
To online user client application invokes “
Collapse
Copy Code
So this method returns the user collection object which was created in “
Collapse
Copy Code
On the server side, the “
Collapse
Copy Code
Now the server has deleted your name from the online user list.
//if" (!theForm) { theform="document.aspnetForm;
}
function" __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET. value="eventTarget;
" theForm.__EVENTARGUMENT. value="eventArgument;
" theForm.submit();
}
}
//]]>
转载:http://www.codeproject.com/KB/gadgets/textchat.aspx
Visit my personal technical blog on Socket Programming in C#
Introduction
This is a chat room application. It can run on LAN or Internet. When user logs in to that server, then he/she will be automatically logged in a default chat room. Every one can chat within that room and their messages will be broadcasted in that room.User Manual
To run the application, first you have to run the server application. Then you will get one Window with two buttons ‘Start’ and ‘Stop’ as screenshot. Your have to run the server by pressing the Start button.Now run the client application. Here you will first get a Window which will ask your name and server address, port, etc. If you try with the same machine, then the given address is ok. But if it is a different address, then you need to update ‘
localhost’ with a particular IP address or host name. But do not change the port number and remaining things and press enter or click on join button. See the screenshot.
Now the chat room window will appear. Here there are three sections. The left and large one is the chat history, the right list is for online users, the bottom area for entering your text and send button for sending message to the server.
Remoting Technology - Basic and Simple Architecture
The basic and simple architecture of .NET Remoting technology has three parts. These are:Base Remoting class: This is like a bridge to communicate between Client and Server. It exists in a DLL file which shares Server and Client program.
Server class: It is a server to serve Client requests. Every client connects to Server to communicate with each other. This program holds a Remoting class’s DLL.
Client class: This is the client part of Remoting architecture. This also holds a copy of Remoting base DLL. It connects to Server and via server communicates to other client.
This is very simple idea of Remoting architecture. If you want to learn about this technology, then you may read from the MSDN site.
About the Application
I will describe a Global Text Chat Room application using this technology. This is very easy to develop and interesting also.As Remoting architecture here has a base class (class library) and after compiling, produces a DLL file with name ‘RemoteBase.dll’. This DLL has about six methods like:
JoinToChatRoom
LeaveChatRoom
SendMsgToSvr(Send Message To Server)
GetMsgFromSvr(Get Message From Server), etc.
The next one is the Server, this is a Windows Form (WinForms) application. This application uses ‘RemoteBase.dll’ as its reference file for library. Server registers a TCP channel with a port number. You may choose any port number from 1025 to 65k. And it registers for well known type of
RemoteBaseand mode type is
Singleton. (Remember it should not work for
Singlecalltype, details and differences will be found on MSDN).
When you run the server, you will see a window as the attached screen shot and need to press button ‘Start’ to start the server and check server status as ‘Running’. To stop the server, you need to press on ‘Stop’ button.
The last one is the Client part, it is also a Windows form (
WinForm) application with two forms. Like the server, client also takes reference of ‘RemoteBase.dll’ for library. When you run this client application, one popup window will come and ask for your name which will be used in the chat room to represent you. Then press on Join button. After that, the chat room window will open.
There also is a server address like ‘tcp://localhost:8080/HelloWorld’ here ‘localhost’ is the server address and 8080 is the port number. Server address needs to tell where your server is running. I am using server and client in the same machine so server address is ‘localhost’, you may give any IP address here. Port number can also be changed but server opening port number and client requesting port number should be the same. You cannot change the remaining things in address, otherwise this chat application will not work.
Chat room window has four sections, the largest one to see all chat messages and below that to type chat message, and send button to send message to server. Just above is the list to display all online users.
When you put your name, then client application creates a remote base class’s object and connects to server by registering TCP channel. Then it connects to Chat Room and seeks the latest message number. After that, the main Chat Room window opens. From that window, it seeks the latest available message in the server by a timer. To get message from server, it invokes ‘
GetMsgFromSvr()’, and gets available online user through ‘
GetOnlineUser(), and user message sends from client application to server by invoking ‘
SendMsgToSvr()’. For better understanding, you may go through the code.
How the Code is Working
Start the Server
When users are trying start Server by clicking Start button, the following code executes:Collapse
Copy Code
private void btnStart_Click(object sender, EventArgs e) { if (channel == null) { channel = new TcpChannel(8080); ChannelServices.RegisterChannel(channel, false); RemotingConfiguration.RegisterWellKnownServiceType (typeof(SampleObject), "ChatRoom", WellKnownObjectMode.Singleton); lblStatus.Text = "Running..."; btnStart.Enabled = false; btnStop.Enabled = true; } }
Here a
TcpChannelopens with port number 8080 and register it as
WellKnownServiceType. ‘
ChatRoom’ is the ‘
ObjectUri’ it will require to connect to server from client.
On the other hand, when user presses ‘Stop’ server, then unregister the channel and stop the server. The code is shown below:
Collapse
Copy Code
private void btnStop_Click(object sender, EventArgs e) { if (channel != null) { ChannelServices.UnregisterChannel(channel); channel = null; lblStatus.Text = "Stopped."; btnStart.Enabled = true; btnStop.Enabled = false; } }
Join ChatRoom
Next comes the client, how client connects to server and user logs in to the chat room. To join the chat room, the below code is executed:Collapse
Copy Code
private void JoinToChatRoom() { if (chan == null && txtName.Text.Trim().Length != 0) { chan = new TcpChannel(); ChannelServices.RegisterChannel(chan,false); // Create an instance of the remote object objChatWin = new frmChatWin(); objChatWin.remoteObj = (SampleObject)Activator.GetObject (typeof(RemoteBase.SampleObject), txtServerAdd.Text); if (!objChatWin.remoteObj.JoinToChatRoom(txtName.Text)) { MessageBox.Show(txtName.Text+ " already joined, please try with different name"); ChannelServices.UnregisterChannel(chan); chan = null; objChatWin.Dispose(); return; } objChatWin.key = objChatWin.remoteObj.CurrentKeyNo(); objChatWin.yourName= txtName.Text; this.Hide(); objChatWin.Show(); } }
Here from the user, the client application takes a name and checks with the server if the name is available or not. If the name is available, then user gets the ‘
CurrentKeyNo’ of server, it is the number of last chat message (how the key is generated, described later) and open the ChatRoom window.
If user name is already taken by another user, then the application asks the user for a different name.
On the server side to join a user in chat server “
JoinToChatRoom()” method is invoked. Let's see what happens within the method:
Collapse
Copy Code
public bool JoinToChatRoom(stringname) { if (alOnlineUser.IndexOf(name) > -1) return false; else { alOnlineUser.Add(name); SendMsgToSvr(name + " has joined into chat room."); return true; } }
Here the user can successfully log in to the server, then his name is added in a user collection, ‘
alOnlineUser’ is an
ArrayListtype object.
Send Message to Server[/b]
When user types some message and presses on the ‘Send’ button or just presses ‘Enter’ button, then the client application tries to send a message to the server. To do it, the client calls the below method:Collapse
Copy Code
private void SendMessage() { if (remoteObj != null && txtChatHere.Text.Trim().Length>0) { remoteObj.SendMsgToSvr(yourName + " says: " + txtChatHere.Text); txtChatHere.Text = ""; } }
Here client application invokes the “
SendMsgToSvr()” method of the server. Let’s see what the method is doing:
Collapse
Copy Code
public void SendMsgToSvr(stringchatMsgFromUsr) { hTChatMsg.Add(++key, chatMsgFromUsr); }
Wow! This is very small code. Actually this is adding the users’ message to another collection. I have used for this collection of
HashTabletype, you may use any other collection type to store
stringdata.
See here there is one counter ‘key’ which is incrementing by one. This is the counter which is maintaining the chat message number. It will help us to get the chat message from server.
Receive Message from Server Ok friends, next we look at how data is got from the server.
In chat room a timer always fires which tries to get a message from the server and current available user in server. Here the below code plays in the Client side:Collapse
Copy Code
private void timer1_Tick(object sender, EventArgs e)
{
if (remoteObj != null)
{
stringtempStr = remoteObj.GetMsgFromSvr(key);
if (tempStr.Trim().Length > 0)
{
key++;
txtAllChat.Text = txtAllChat.Text + "\n" + tempStr;
}
ArrayListonlineUser = remoteObj.GetOnlineUser();
lstOnlineUser.DataSource = onlineUser;
skipCounter = 0;
if (onlineUser.Count < 2)
{
txtChatHere.Text = "Please wait until atleast two user join in Chat Room.";
txtChatHere.Enabled = false;
}
else if(txtChatHere.Text == "Please wait untill atleast two user join in Chat Room."
&& txtChatHere.Enabled == false)
{
txtChatHere.Text = "";
txtChatHere.Enabled = true;
}
}
}
Here client invokes “
GetMsgFromSvr()” method to get a message, with parameter key. The code of the method is:
Collapse
Copy Code
public stringGetMsgFromSvr(int lastKey)
{
if (key > lastKey)
return hTChatMsg[lastKey + 1].ToString();
else
return "";
}
The server just takes the key as last-key of user’s message and uses it in Chat message collection to fetch the next chat message, after that the message returns to the client.
To online user client application invokes “
GetOnlineUser()” method, let's see what happens in the server side within the method.
Collapse
Copy Code
public ArrayListGetOnlineUser()
{
return alOnlineUser;
}
So this method returns the user collection object which was created in “
JoinToChatRoom()” method.
Leave the Chat Room[/b]
When user closes the chat room, then client application requests the server to remove his/her name from server’s online user list. On the client side, the below method invokes:Collapse
Copy Code
private void Form1_FormClosed(object sender, FormClosedEventArgs e) { if (remoteObj != null) { remoteObj.LeaveChatRoom(yourName); txtChatHere.Text = ""; } Application.Exit(); }
On the server side, the “
LeaveChatRoom()” method is invoked. The code of that method is:
Collapse
Copy Code
public void LeaveChatRoom(stringname)
{
alOnlineUser.Remove(name);
SendMsgToSvr(name + " has left the chat room.");
}
Now the server has deleted your name from the online user list.
//if" (!theForm) { theform="document.aspnetForm;
}
function" __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET. value="eventTarget;
" theForm.__EVENTARGUMENT. value="eventArgument;
" theForm.submit();
}
}
//]]>
License
This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)转载:http://www.codeproject.com/KB/gadgets/textchat.aspx
相关文章推荐
- Chat Application using Web services in C#(转载)
- .Net Remoting 事件回调 Client 函数方法完整实例: C# 实现控制台网络聊天室 (Console Remoting ChatRoom)
- Multi User Chat Room Using ASP.NET 2.0 and AJAX
- Application Scheduler Service Using C#.Net And XML
- Creating a LINQ Enabled ASP.NET Web application template using C#.[转]
- [C#.NET][VB.NET] Winform 應用程式等級的例外捕捉 / Winform of Application Level wicth Exception Catch(转载)
- Simple FTP demo application using C#.Net 2.0
- ASP.NET Core Building chat room using WebSocket
- Create, Read, Write, Copy, Move and Delete a Text File using C# and VB.NET
- Remoting in .NET Using C#
- How To Implement Forms-Based Authentication in Your ASP.NET Application by Using C# .NET
- How to Use .Net Remoting Using C#
- ASP.NET 调试出现<%@ Application Codebehind="Global.asax.cs" Inherits="XXX.XXX.Global" Language="C#" %>
- 【转载】Using the Web Service Callbacks in the .NET Application
- C# .NET - Sql Bulk Insert from multiple delimited Textfile using c#.net
- Building an AJAX Based Web Chatting Application using ASP.NET 2.0(转载)
- MVC architecture in ASP.Net using C# and Microsoft Data Access Application block
- 分析器错误 <%@ Application Codebehind="Global.asax.cs" Inherits="erfang.web.Global" Language="C#" %>
- Full-Text Search in ASP.NET using Lucene.NET
- 转载ASP.NET 状态管理Application,Session,Cookie和ViewState用法