23
LẬP TRÌNH CHAT LẬP TRÌNH CHAT UDP - TCP Chat UDP (User Datagram Protocol) - Không hướng kết nối Server.cs CODE using System; using System.Net.Sockets; using System.Net; using System.Text; namespace ChatUDP_051011 { class Program { static void Main(string[] args) { // tao mot socket Socket socketServer= new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // tao mot ip client IPEndPoint ipEndPoint= new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080); socketServer.Bind(ipEndPoint); // tao ra mot endpoint tu xa de nhan data ve IPEndPoint remoteIPEndPoint= new IPEndPoint(IPAddress.Any, 0); EndPoint remoteEndPoint = (EndPoint) remoteIPEndPoint; Console.WriteLine("Server dang mo cua");

COCE LẬP TRÌNH CHAT

Embed Size (px)

Citation preview

Page 1: COCE LẬP TRÌNH CHAT

LẬP TRÌNH CHAT 

LẬP TRÌNH CHAT UDP - TCP 

Chat UDP (User Datagram Protocol) - Không hướng kết nối Server.cs 

CODE

using System;using System.Net.Sockets;using System.Net;using System.Text;

namespace ChatUDP_051011{   class Program   {       static void Main(string[] args)       {           // tao mot socket           Socket socketServer= new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);                      // tao mot ip client           IPEndPoint ipEndPoint= new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);           socketServer.Bind(ipEndPoint);

           // tao ra mot endpoint tu xa de nhan data ve                      IPEndPoint remoteIPEndPoint= new IPEndPoint(IPAddress.Any, 0);           EndPoint remoteEndPoint = (EndPoint) remoteIPEndPoint;

           Console.WriteLine("Server dang mo cua");                      // nhan du lieu tu client           byte[] dataArr= new byte[1024];           int length = socketServer.ReceiveFrom(dataArr, ref remoteEndPoint);

           string data = Encoding.ASCII.GetString(dataArr, 0, length);           Console.WriteLine("Client: {0}", data);

           // gui data cho client           dataArr = Encoding.ASCII.GetBytes("Chao Client");           socketServer.SendTo(dataArr, remoteEndPoint);          

Page 2: COCE LẬP TRÌNH CHAT

           // nhan du lieu           while (true)           {               // nhan data               dataArr= new byte[1024];               length = socketServer.ReceiveFrom(dataArr, ref remoteEndPoint);               data = Encoding.ASCII.GetString(dataArr, 0, length);               if(data.ToUpper().Equals("EXIT"))                   break;               Console.WriteLine("Client: {0}",data);

               // gui data               Console.Write("Server: ");               data = Console.ReadLine();

               dataArr = Encoding.ASCII.GetBytes(data);               socketServer.SendTo(dataArr, dataArr.Length, SocketFlags.None, remoteEndPoint);                          }           socketServer.Close();       }   }}

Client.csCODE

using System;using System.Net;using System.Net.Sockets;using System.Text;

namespace ChatUDP_051011_Client{   class Program   {       static void Main(string[] args)       {           // tao socket           Socket socketClient= new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

           // xac dinh dia chi ip server           IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);

Page 3: COCE LẬP TRÌNH CHAT

                      // gui den server           string data = "Chao Server";           byte[] dataArr= new byte[1024];           dataArr = Encoding.ASCII.GetBytes(data);           socketClient.SendTo(dataArr, ipEndPoint);

           // nhan du lieu           EndPoint remoteEndPoint = (EndPoint) ipEndPoint;           dataArr= new byte[1024];           int length = socketClient.ReceiveFrom(dataArr, ref remoteEndPoint);           data = Encoding.ASCII.GetString(dataArr, 0, length);           Console.WriteLine("Server: {0}", data);

           while (true)           {               // gui cho server                Console.Write("Client: ");               data = Console.ReadLine();               dataArr = Encoding.ASCII.GetBytes(data);               socketClient.SendTo(dataArr, data.Length, SocketFlags.None, remoteEndPoint);

               if(data.ToUpper().Equals("EXIT"))                   break;                              // nhan du lieu               dataArr= new byte[1024];               length = socketClient.ReceiveFrom(dataArr,ref remoteEndPoint);               data = Encoding.ASCII.GetString(dataArr, 0, length);               Console.WriteLine("Server: {0}", data);           }                      // dong ket noi           socketClient.Close();       }   }}

Chat TCP (Transport Control Protocol) - Hướng kết nối 

Server.cs CODE

using System;

Page 4: COCE LẬP TRÌNH CHAT

using System.Net;using System.Net.Sockets;using System.Text;

namespace ChatTCP_061011{   class Program   {       static void Main(string[] args)       {           // tao mot socket           Socket socketServer= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                      // tao mot ip client           IPEndPoint ipEndPoint= new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);           socketServer.Bind(ipEndPoint);

           // lang nghe ket noi, 10 ket noi           socketServer.Listen(10);           Console.WriteLine("Dang lang nghe ket noi");

           // chap nhan ket noi           Socket socketClient= socketServer.Accept();           Console.WriteLine("Da chap nhan ket noi");           Console.WriteLine("Chap nhan ket noi tu client {0}", socketClient.RemoteEndPoint.ToString());

           // Loi chao mung den client tu server           string data = "Chao mung da den voi Server";                      // chuyen chuoi welcome thanh mang byte           byte[] dataArr = new byte[1024];           dataArr = Encoding.ASCII.GetBytes(data);

           // gui du lieu theo mang byte           socketClient.Send(dataArr, dataArr.Length, SocketFlags.None);

           // nhan du lieu           while (true)           {               dataArr= new byte[1024];

               // kiem tra rong               int length = socketClient.Receive(dataArr);               if(length==0)

Page 5: COCE LẬP TRÌNH CHAT

                   break;

               // chuyen kieu byte ve chuoi               data = Encoding.ASCII.GetString(dataArr,0,length);

               Console.Write("Client: {0}", data);

               if(data.ToUpper().Equals("EXIT"))                   break;                              // gui data cho client               Console.Write("\nServer: ");               data = Console.ReadLine();               dataArr= new byte[1024];                              dataArr = Encoding.ASCII.GetBytes(data);               socketClient.Send(dataArr, data.Length, SocketFlags.None);                          }           // dong ket noi           socketClient.Shutdown(SocketShutdown.Both);           socketClient.Close();           socketServer.Close();       }   }}

Client.cs CODE

using System;using System.Net;using System.Net.Sockets;using System.Text;

namespace ChatTCP_061011_Client{   class Program   {       static void Main(string[] args)       {           // tao socket           Socket socketClient= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

Page 6: COCE LẬP TRÌNH CHAT

           // xac dinh dia chi ip server           IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);                      // ket noi den server           socketClient.Connect(ipEndPoint);

           // nhan du lieu           byte[] dataArr= new byte[1024];           int length = socketClient.Receive(dataArr);

           // convert ve string           string data = Encoding.ASCII.GetString(dataArr, 0, length);

           // hien thi           Console.Write("\nServer: {0}", data);

           while (true)           {               // gui cho server                Console.Write("\nClient: ");               data = Console.ReadLine();

               dataArr = Encoding.ASCII.GetBytes(data);               socketClient.Send(dataArr, data.Length, SocketFlags.None);

               if(data.ToUpper().Equals("EXIT"))                   break;                              // nhan du lieu               length = socketClient.Receive(dataArr);               data = Encoding.ASCII.GetString(dataArr, 0, length);               Console.Write("Server: {0}",data);           }                      // dong ket noi           socketClient.Disconnect(true);           socketClient.Close();       }   }}

General - October 7, 2011 09:15 AM (GMT)LẬP TRÌNH CHAT TCP Listener Client - UDP Client 

TCP Listener Client 

Page 7: COCE LẬP TRÌNH CHAT

TCPListener.cs CODE

using System;using System.Net.Sockets;using System.Net;using System.IO;

namespace ChatTCPListenerClient_061011{   class Program   {       static void Main(string[] args)       {           // tao server           IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);           TcpListener tcpListener = new TcpListener(ipEndPoint);

           // bat server, lang nghe ket noi           tcpListener.Start();           Console.WriteLine("Server dang lang nghe ket noi");

           // chap nhan ket noi           TcpClient tcpClient = tcpListener.AcceptTcpClient();           Console.WriteLine("Da ket noi voi Client");

           // tao vung dem nhap xuat           StreamReader sr = new StreamReader(tcpClient.GetStream());           StreamWriter sw = new StreamWriter(tcpClient.GetStream());

           while (true)           {               // lay data tu client               string dataReceive = sr.ReadLine();               Console.WriteLine("Client: " + dataReceive);

               // gui data den client               Console.Write("Server: ");               string dataSend = Console.ReadLine();                //sw.Write(dataSend) la chuong trinh died day sw.WriteLine(dataSend);                               // xoa het dem cho cac dong nay               sw.Flush();

Page 8: COCE LẬP TRÌNH CHAT

           }           sr.Close();           sw.Close();           tcpClient.Close();       }   }}

TCPClient.cs CODE

using System;using System.Net;using System.Net.Sockets;using System.IO;

namespace ChatTCPListenerClient_061011_Client{   class Program   {       static void Main(string[] args)       {           // tao mot client           IPEndPoint ipEndPoint= new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);           TcpClient tcpClient= new TcpClient();

           // ket noi den server           tcpClient.Connect(ipEndPoint);           Console.WriteLine("Da ket noi voi Server");

           // tao vung dem nhap xuat           StreamReader sr= new StreamReader(tcpClient.GetStream());           StreamWriter sw= new StreamWriter(tcpClient.GetStream());

           while (true)           {               // gui du lieu den server               Console.Write("Client: ");               string dataSend = Console.ReadLine();                //sw.Write(dataSend) la chuong trinh died day sw.WriteLine(dataSend);

               // xoa het dem cho cac dong nay               sw.Flush();

Page 9: COCE LẬP TRÌNH CHAT

               // nhan du lieu               string dataReceive = sr.ReadLine();               Console.WriteLine("Server: "+dataReceive);           }           sr.Close();           sw.Close();           tcpClient.Close();       }   }}

UDP Client 

Copy ra 2 cái là nó tự chạy thôi. Không phân biệt chủ tớ ~~

UDPClient.cs CODE

using System;using System.Text;using System.Net;using System.Net.Sockets;

namespace ChatUDPClient_061011{   class Program   {       static void Main(string[] args)       {           while (true)           {               sendData();               }           

           receiveData();           Console.ReadLine();       }

       static void sendData()       {           // tao doi tuong udpclient           UdpClient udpClientSender = new UdpClient();

Page 10: COCE LẬP TRÌNH CHAT

           IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);

           // gui data           string data = Console.ReadLine();           byte[] dataArr = new byte[1024];           dataArr = Encoding.UTF8.GetBytes(data);           udpClientSender.Send(dataArr, dataArr.Length, ipEndPoint);       }

       static void receiveData()       {           UdpClient udpClientReceiver= new UdpClient(80); // local port           IPEndPoint ipEndPoint= new IPEndPoint(IPAddress.Any, 0);

           while (true)           {               byte[] dataArr= new byte[1024];               dataArr = udpClientReceiver.Receive(ref ipEndPoint);               string data = Encoding.UTF8.GetString(dataArr, 0, dataArr.Length);               Console.WriteLine(data);           }       }   }}

General - October 7, 2011 09:17 AM (GMT)LẬP TRÌNH CHAT Asynchoronous (Không đồng bộ) 

Như ở trên các bạn thấy. Khi server giao tiếp với Client. Chúng ta gửi một tin nhắn, thì phải đợi một tin nhắn từ Client gửi lại thì chúng ta mới gửi tiếp được. Vậy làm sao chúng ta gửi nhiều lần được --> giải pháp là không đồng bộ

Hướng giải quyết Biến toàn cục:- private Socket server, client- private string data- private byte[] dataArr = new byte[1024];

- Ta cần xây dựng ít nhất 4 hàm:---- +) void initialChat()---- +) void Accept(IAsyncResult iar) ở Server và void Connect(IAsyncResult iar) ở Client---- +) void ReceiveData(IAsyncResult iar)---- +) void SendData(IAsyncResult iar)

Page 11: COCE LẬP TRÌNH CHAT

Server.cs CODE

using System;using System.Text;using System.Windows.Forms;using System.Net;using System.Net.Sockets;using System.Drawing;

namespace ChatTCPAsyc_071011{   class Program : Form   {       private TextBox conStatus;       private ListBox results;       private byte[] data= new byte[1024];       private int size = 1024;       private Socket server;

       static void Main(string[] args)       {           Application.Run(new Program());       }

       public Program()       {           Text = "Asynchoronous TCP Server";           Size = new Size(400, 800);

           results= new ListBox();           results.Parent = this;           results.Location=new Point(10,65);           results.Size= new Size(350,20*Font.Height);                      Label label1 = new Label();           label1.Parent = this;           label1.Text = "Text received from client:";           label1.AutoSize = true;           label1.Location=new Point(10,45);                      Label label2= new Label();           label2.Text = "Connection Status: ";           label2.AutoSize = true;           label2.Location=new Point(10,330);

Page 12: COCE LẬP TRÌNH CHAT

                      conStatus= new TextBox();           conStatus.Parent = this;           conStatus.Text = "Waiting for client...";           conStatus.Size= new Size(200,2*Font.Height);           conStatus.Location=new Point(110,325);                      Button stopServer= new Button();           stopServer.Parent = this;           stopServer.Text = "StopServer";           stopServer.Location=new Point(260,32);           stopServer.Size= new Size(7*Font.Height, 2*Font.Height);           stopServer.Click+= new EventHandler(ButtonStopOnClick);                      server= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);           IPEndPoint iep= new IPEndPoint(IPAddress.Any, 9050);           server.Bind(iep);           server.Listen(5);           server.BeginAccept(new AsyncCallback(AcceptConn), server);                  }

       void ButtonStopOnClick(object sender, EventArgs e)       {           Close();       }

       void AcceptConn(IAsyncResult iar)       {           Socket oldserver = (Socket) iar.AsyncState;           Socket client = oldserver.EndAccept(iar);           conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();           string stringData = "Welcome to my server";           byte[] message1 = Encoding.ASCII.GetBytes(stringData);           client.BeginSend(message1, 0, message1.Length, SocketFlags.None, new AsyncCallback(SendData), client);       }              void SendData(IAsyncResult iar)       {           Socket client = (Socket) iar.AsyncState;           int sent = client.EndSend(iar);           client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client);

Page 13: COCE LẬP TRÌNH CHAT

       }

       void ReceiveData(IAsyncResult iar)       {           Socket client = (Socket) iar.AsyncState;           int recv = client.EndReceive(iar);           if(recv==0)           {               client.Close();               conStatus.Text = "Waiting for client ...";               server.BeginAccept(new AsyncCallback(AcceptConn), server);               return;           }

           string receivedData = Encoding.ASCII.GetString(data, 0, recv);           results.Items.Add(receivedData);           byte[] message2 = Encoding.ASCII.GetBytes(receivedData);           client.BeginSend(message2, 0, message2.Length, SocketFlags.None, new AsyncCallback(SendData), client);       }           }}

Client.cs CODE

using System;using System.Text;using System.Net.Sockets;using System.Net;using System.Drawing;using System.Windows.Forms;

namespace ChatTCPAsyc_071011_Client{   class Program:Form   {       private TextBox newText;       private TextBox conStatus;       private ListBox results;       private Socket client;       private byte[] data= new byte[1024];       private int size = 1024;

Page 14: COCE LẬP TRÌNH CHAT

       static void Main(string[] args)       {           Application.Run(new Program());       }

       public Program()       {           Text = "Asynchoronous TCP Client";           Size = new Size(400, 380);                      Label label1= new Label();           label1.Parent = this;           label1.Text = "Enter text string";           label1.AutoSize = true;           label1.Location= new Point(10,30);                      newText=new TextBox();           newText.Parent = this;           newText.Size=new Size(200,2*Font.Height);           newText.Location= new Point(10,55);                      results= new ListBox();           results.Parent = this;           results.Location= new Point(10,85);           results.Size= new Size(360,18*Font.Height);                      Label label2 = new Label();           label2.Parent = this;           label2.Text = "Connection Status:";           label2.AutoSize = true;           label2.Location=new Point(10,330);                      conStatus= new TextBox();           conStatus.Parent = this;           conStatus.Text = "Disconected";           conStatus.Size=new Size(200, 2*Font.Height);           conStatus.Location= new Point(110,325);                      Button sendit= new Button();           sendit.Parent = this;           sendit.Text = "Send";           sendit.Location=new Point(220,52);           sendit.Size= new Size(5*Font.Height, 2*Font.Height);           sendit.Click+= new EventHandler(ButtonSendOnClick);                      Button connect = new Button();

Page 15: COCE LẬP TRÌNH CHAT

           connect.Parent = this;           connect.Text = "Connect";           connect.Location=  new Point(295,20);           connect.Size= new Size(6*Font.Height, 2*Font.Height);           connect.Click+= new EventHandler(ButtonConnectOnClick);                      Button discon= new Button();           discon.Parent = this;           discon.Text = "Disconect";           discon.Location= new Point(295,52);           discon.Size=new Size(6*Font.Height, 2*Font.Height);           discon.Click+= new EventHandler(ButtonDisconOnClick);

       }       void ButtonConnectOnClick(object sender, EventArgs e)       {           conStatus.Text = "Connecting...";           Socket newsock= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);           IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);           newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);       }

       void ButtonSendOnClick(object obj, EventArgs ea)       {           byte[] message = Encoding.ASCII.GetBytes(newText.Text);           newText.Clear();           client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(SendData), client);

       }

       void ButtonDisconOnClick(object obj, EventArgs ed)       {           client.Close();           conStatus.Text = "Disconnected";       }

       void Connected(IAsyncResult iar)       {           client = (Socket) iar.AsyncState;           try           {               client.EndConnect(iar);               conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();               client.BeginReceive(data, 0, size, SocketFlags.None, new

Page 16: COCE LẬP TRÌNH CHAT

AsyncCallback(ReceiveData), client);           }           catch (SocketException)           {               conStatus.Text = "Error connecting";           }       }

       void ReceiveData(IAsyncResult iar)       {           Socket remote = (Socket) iar.AsyncState;           int recv = remote.EndReceive(iar);           string stringData = Encoding.ASCII.GetString(data,0,recv);           results.Items.Add(stringData);       }

       void SendData(IAsyncResult iar)       {           Socket remote = (Socket) iar.AsyncState;           int sent = remote.EndSend(iar);           remote.EndSend(iar);           remote.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), remote);       }   }}

General - October 7, 2011 09:27 AM (GMT)LẬP TRÌNH CHAT VỚI MULTI THREAD 

Như ở trên. 

Khi ta mở một server (client), rồi mở tiếp một client (server) kết nối với server (client) đó. Khi đó chúng ta mở thêm nhiều client (server) nữa thì nó chỉ kết nối chứ không thực hiện gì được với client (server) kia - đấy là với giao thức hướng kết nối. Còn với giao thức không hướng kết nối thì thằng nào gửi tin đến cho nó thì nó sẽ gửi lại cho cái thắng liên lạc gần lúc nó gửi tin nhất, tức là liên kết cuối cùng trước khi nó gửi tin.

Vì đơn giản chỉ có một luồng xử lý kết nối server với client đầu. Muốn một server (client) xử lý với nhiều client (server) thì ta tạo ra nhiều luồng dữ liệu trên server (client) là ngon canh ngay - đấy là với giao thức hướng kết nối. Còn với giao thức phi kết nối thì không thể đa luồng được vì nó có hoạt động theo luồng nào đâu, cứ thằng nào đến với nó gần lúc nó gửi tin nhất thì nó chơi với thằng ấy

Page 17: COCE LẬP TRÌNH CHAT

Viết lại Server của TCP Listener nhéServer.cs

CODE

using System;using System.Net;using System.Net.Sockets;using System.Threading;using System.IO;

namespace ChatTCPListenerClientThread_071011{   class Program   {       static void Main(string[] args)       {           // gan vao mot endpoint cuc bo           IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);           TcpListener tcpListener= new TcpListener(iep);           Console.WriteLine("Dang cho ket noi");

           tcpListener.Start();           while (true)           {               // chap nhan ket noi               TcpClient tcpClient = tcpListener.AcceptTcpClient();                              // tao tuyen moi de xu ly               new ClientThread(tcpClient);           }           tcpListener.Stop();       }   }

   public class ClientThread   {       private Thread _thread;       private TcpClient _tcpClient;              public ClientThread(TcpClient tcpclient)       {           this._tcpClient = tcpclient;           _thread=new Thread(new ThreadStart(sendData));           _thread.Start();

Page 18: COCE LẬP TRÌNH CHAT

       }

       private void sendData()       {           StreamReader sr= new StreamReader(_tcpClient.GetStream());           StreamWriter sw = new StreamWriter(_tcpClient.GetStream());                      while(true)           {               string s = sr.ReadLine();               Console.WriteLine("Client: "+ s);

               // gui du lieu cho client               Console.WriteLine("Server: ");               s = Console.ReadLine();               sw.WriteLine(s);               sw.Flush();           }       }   }}