LEECH Chưởng trình Chat bằng c# : Source : http://totuan.one-forum.net/ki7871n-...ang-c-t486.htm I. Giới thiệu Chương trình cho phép thực hiện việc giao tiếp giữa các clients thông qua server, II. Nội dung sử dụng luồng tại server, mỗi khi Client kết nối đến server chương trình sẽ tạo những luồng riêng biệt để xử lý các kết nối, chương trình cũng tạo ra những luồng để xử lý các Client mới. Chương trình được mô tả cụ thể như sau: Chương trình ThreadedTcpSrvr.cs using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; class ThreadedTcpSrvr private TcpListener client; public ThreadedTcpSrvr() _ client = new TcpListener(9050); client.start(); Console.WriteLine("Waiting for clients..."); while(true) while ( client.pendingo) Thread.Sleep(1000); ionthread newconnection = new ionthread(); newconnection.threadlistener = this.client; Thread newthread = new Thread(new ThreadStart(newconnection.Handleion)); newthread.start(); public static void Main() ThreadedTcpSrvr server = new ThreadedTcpSrvr(); class ionthread public TcpListener threadlistener; private statin int. connections = 0; public void Handleion() int recv; byte[] data = new byte[1024]; TcpClient client = threadlistener.accepttcpclient(); Networkstream ns = client.getstream(); connections++; Console.WriteLine("New client accepted: 0 active connections",
connections); string welcome = ""; data = Encoding.ASCII.GetBytes(welcome); ns.write(data, 0, data.length); while(true) data = new byte[1024]; recv = ns.read(data, 0, data.length); if (recv == 0) break; ns.write(data, 0, recv); ns.close(); client.close(); connections Console.WriteLine("Client disconnected: 0 active connections", connections); Chương trình sử dụng lớp Tcp Listener để lắng nghe các kết nối TCP theo cổng cố định (9050) đồng thời phương thức starto được sử dụng để chờ các clients mới. while(true) while (!client.pendingo) Thread.Sleep(1000); ionthread newconnection = new ionthread(); newconnection.threadlistener = this.client; Thread newthread = new Thread(new ThreadStart(newconnection.Handleion)); newlhread.slarl(); Vòng lặp while được sử dụng để kiểm tra các Client kết nối, nếu có chương trình sẽ tạo luồng để chấp nhận các kết nối. Khi server chấp nhận các kết nối từ phía Client, nó sẽ tạo ra socket riêng biệt và đưa vào một luồng mới. Một Client có thể gửi tin nhắn đến một Client và nhận được phản hồi từ chính Client đó mà không ảnh hưỏng đến các Client khác. Khi mỗi Client ngắt kết nối, luồng sẽ tự động ngắt. Chương trình dưới đây thực hiện việc gửi và nhận dữ liệu giữa các Client thông qua giao thức TCP Chương trình TCPChat.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms;
using System.Net.Sockets; using System.Net; using System.Threading; namespace TcpChat public partial class TcpChat : Form public TcpChatQ InitializeComponent(); private static Socket client; private static byte[] data = new byte[1024]; void AcceptConn(IAsyncResult iar) Socket oldserver = (Socket)iar.AsyncState; client = oldserver.endaccept(iar); results.items.add("ion from: " + client.remoteendpoint.tostring()); Thread receiver = new Thread(new ThreadStart(ReceiveData)); receiver.start(); void ed(iasyncresult iar) try client.end(iar); results.items.add("ed to: " + client.remoteendpoint.t ost ring ()); Thread receiver = new Thread(new ThreadStart(ReceiveData)); receiver.start(); catch (SocketException) results.items.add("error connecting"); void Data(IAsyncResult iar) Socket remote = (Socket)iar.AsyncState; int sent = remote.end(iar); void ReceiveData() int recv; string stringdata; while (true) recv = client.receive(data); stringdata = Encoding.ASCII.GetString(data, 0, recv); if (stringdata == "bye") break; results.items.add(stringdata); stringdata = "bye"; byte[] message = Encoding.ASCII.GetBytes(stringData); client.(message); client. CloseQ;
results.items.add("ion stopped"); return; private void btnlisten_click(object sender, EventArgs e) results.items.add("listening for a client..."); Socket newsock = new Socket(AddressFamily.InterNetwork, SccketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); newsock.bind(iep); newsock.listen(5); newsock.beginaccept(new AsyncCallback(AcceptConn), newsock); private void btnconnect_click(object sender, EventArgs e) results.items.add(""); client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse(txtip.Text), 9050); client.begin(iep, new AsyncCallback(ed), client); private void btnsend_click(object sender, EventArgs e) byte[] message = Encoding.ASCII.GetBytes(txttext.Text); txttext.clear(); client.begin(message, 0, message.length, 0, new AsyncCallback(Data), client); Chương trình được tạo dưới dạng form đơn giản với các đối tượng cụ thể sau: 0 Một textbox (txtip) cho phép nhập địa chỉ ip kết nối 0 Textbox (txttext): nhập nội dung gửi đi 0 Nút listen chờ nhận kết nối từ máy Client khác 0 Nút connect thực hiện các kết nối đến các máy khác từ xa 0 Nũt send thực hiện gửi tin nhắn đến các máy Client được nhập vào từ textbox (txttext). 0 Listbox (result) hiển thị nội dung Chat giữa các Client với nhau. 0 Khi ngưòi dùng nhấn nút listen một socket sẽ được tạo ra và lắng nghe các kết nối đang đến sử dụng phương thức beginacceptq: private void htn1.isten_click(object sender, EventArgs e) results.items.add("listening for a client..."); Socket newsock = new Socket(AddressFamily.InterNetwork, SccketType.Stream, ProtocolType.Tcp); IPEndPoint iep - new IPEndPoint(IPAddress.Any, 9050); newsock.bind(iep); newsock.listen(5);
newsock.beginaccept(new AsyncCallback(AcceptConn), newsock); Khi một chương trình chat khác kết nối., phương thức AcceptConnO tạo ra những socket riêng biệt cho mỗi Client. Khi khách hàng nhấn nút connect, một socket được tao ra và cố gắng để kết nối đến host từ xa, sử dụng phương thức beginconnect(). Sau khi host từ xa chấp nhận kết nối. Một socket được đưa đến luồng tạm thời, mục đích của luồng tạm thời này là chờ dữ liệu đến và đưa dữ liệu vào trong listbox void ReceiveData() int recv; string stringdata; while (true) recv = client.receive(data); stringdata = Encoding.ASCII.GetString(data, 0, recv); if (stringdata == "bye") break; results.items.add(stringdata); stringdata = "bye"; byte[] message = Encoding.ASCII.GetBytes(stringData); client.(message); client.close(); results.items.add("ion stopped"); return; Khi dữ liệu gửi đi có chuỗi bye, chương trình sẽ tự động đóng Socket, cả hai chương trình Chat bị ngắt và đóng kết nối Tcp. Minh họa chương trình Chat giữa 2 Client thông qua server: Chương trình được minh họa trên 2 máy khác nhau, máy 1 với địa chĩ ip: 172.16.71.13 đóng vai trò là máy server và Client, máy 2 với địa chỉ ip: 172.17.71.160 là máy Client Đầu tiên chạy chương trình ThreadedTcpSrvr trên máy 1
CÃ D:\Tmp\ThreadedTcpSrvr\ThreadedTcpSrvr\bin\Debug\ThreadedTcpSrvr.exe Mỏ chương trình TcpChat tại máy 1 và máy 2. Giả sử hai chương trình này được chạy cùng thời điểm đang xét. TcpChat I Máy 1 Ä l ü T c p C h a t 1 Máy 2 Nhap Dia chi IP 172.16.71 13 Listen Nhap Dia chi IP 172.16.71.13 Listen ed to: 172.16.71.13:9050 ed to: 172.16.71.13:9050 Bây giò bắt đầu kết nối 2 Client để Chat trực tiếp với nhau. Giả sử máy 2 giữ vai trò chà kết nối nhấn nút Listen. Máy 1 sẽ giữ vai trò kết nối, nhập địa chỉ ip máy 2:172.168.71.160 và nhấn nút khi đó 2 Client có thể Chat với nhau trực tiếp.
c' D:\Tmp\23-05-08\ThreadedTcpSrvr\ThreadedTcpSrvr\ThreadedTcpSrvr\bin\Debug\Thread... EBÜ W a itin g f o r c l i e n t s... Neu c l i e n t a c c e p te d : 1 a c t i v e c o n n e c tio n s Neu c l i e n t a c c e p te d : 2 a c t i v e c o n n e c tio n s Sau khi k ê t noi diiöc thiét lâp, 2 mây cô the gûri nhân tin nhan qua lai vôi nhau: May 1 I T cpchat Mây 2 Nhap Dia chi IP 172.16.71.1G0 Listen Nhap D» chi IP 172 16 71 13 Listen ed to: 172.16.71 13:9050 ed to: 172.16.71.160:9050 Gui tu may 160 ion stopped ed to: 172.16.71139050 Listening for a csert... ion from 17216.71 13:1677 Gui tu may 13 ion stopped