You are on page 1of 18

LP TRNH CHAT

LP TRNH CHAT UDP - TCP

Chat UDP (User Datagram Protocol) - Khng hng kt ni 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);

// 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.cs
CODE 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);

// 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) - Hng kt ni Server.cs


CODE using System;

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)

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);

// 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)


LP TRNH CHAT TCP Listener Client - UDP Client

TCP Listener Client

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(); } 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(); // nhan du lieu string dataReceive = sr.ReadLine(); Console.WriteLine("Server: "+dataReceive); } sr.Close(); sw.Close(); tcpClient.Close(); } } }

UDP Client Copy ra 2 ci l n t chy thi. Khng phn bit 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(); 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)


LP TRNH CHAT Asynchoronous (Khng ng b)

Nh trn cc bn thy. Khi server giao tip vi Client. Chng ta gi mt tin nhn, th phi i mt tin nhn t Client gi li th chng ta mi gi tip c. Vy lm sao chng ta gi nhiu ln c --> gii php l khng ng b Hng gii quyt Bin ton cc: - private Socket server, client - private string data - private byte[] dataArr = new byte[1024]; - Ta cn xy dng t nht 4 hm: ---- +) void initialChat() ---- +) void Accept(IAsyncResult iar) Server v void Connect(IAsyncResult iar) Client

---- +) void ReceiveData(IAsyncResult iar) ---- +) void SendData(IAsyncResult iar) 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); 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); } 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; 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(); 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 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)


LP TRNH CHAT VI MULTI THREAD

Nh trn. Khi ta m mt server (client), ri m tip mt client (server) kt ni vi server (client) . Khi chng ta m thm nhiu client (server) na th n ch kt ni ch khng thc hin g c vi client (server) kia - y l vi giao thc hng kt ni. Cn vi giao thc khng hng kt ni th thng no gi tin n cho n th n s gi li cho ci thng lin lc gn lc n gi tin nht, tc l lin kt cui cng trc khi n gi tin. V n gin ch c mt lung x l kt ni server vi client u. Mun mt server (client) x l vi nhiu client (server) th ta to ra nhiu lung d liu trn server

(client) l ngon canh ngay - y l vi giao thc hng kt ni. Cn vi giao thc phi kt ni th khng th a lung c v n c hot ng theo lung no u, c thng no n vi n gn lc n gi tin nht th n chi vi thng y Vit li Server ca 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(); } 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(); } } } }

You might also like