Basic Chat Room Applycation in Csharp- Chương trình chat đơn giản
Tuesday, June 15, 2010 9:28:03 AM

-Một demo cơ bản của lập trình socket
-Client gửi bản tin đến server, server broadcast bản tin đến tất cả các client trong Room.
Ý tưởng cơ bản :
-Server active lắng nghe ở một cổng, đợi client kết nối
-Mỗi khi client kết nối, một connection được tạo ra và lưu giữ lại vào list.
// (3) Create a Socket for Each Client and add his Socket to The ArrayList
private static void AddClient(Socket sockClient)
{
Newclient = new SocketClient(sockClient);
ClientsList.Add(Newclient);
// client.Sock.RemoteEndPoint - " has joined the room"
Byte[] byteDateLine = System.Text.Encoding.Unicode.GetBytes(" - Welcome to Our Room - ");
Newclient.ReadOnlySocket.Send(byteDateLine, byteDateLine.Length, 0);
Newclient.SetupRecieveCallback();
}
-Mỗi khi nhận được bản tin từ client, server thực hiện broadcast bản tin tới tất cả các client trong danh sách các kết nối của nó.
// (4) Send The Recieved Data to All Clients in The Room
private static void OnRecievedData(IAsyncResult ar)
{
SocketClient client = (SocketClient)ar.AsyncState;
byte[] aryRet = client.GetRecievedData(ar);
if (aryRet.Length < 1)
{
// client.Sock.RemoteEndPoint - "has left the room"
client.ReadOnlySocket.Close();
ClientsList.Remove(client);
return;
}
foreach (SocketClient clientSend in ClientsList)
{
try
{
clientSend.ReadOnlySocket.Send(aryRet);
}
catch
{
clientSend.ReadOnlySocket.Close();
ClientsList.Remove(client);
return;
}
}
client.SetupRecieveCallback();
}
-Ý tưởng cho việc phát triển sản phẩm chat hỗ trợ chát theo IDUser : lưu danh sách ID đăng kí,client gửi bản tin cho server thay vì cleartext thì đóng gói bản tin lại cho thêm các thông tin header (có thể là ID, IP,.. hoặc đơn giản chỉ là tag header ví dụ patterm dạng [ID]+Data), server bóc tách bản tin thay vì broadcast thì chỉ gửi cho kết nối nào trùng ID đó.
src demo :
http://www.mediafire.com/file/yumimzdmy2n/ChatRoomBasic.rar
--------------have fun && good luck !
---------------












