You are on page 1of 19

using using using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms; System.Net; System.Net.Sockets;

namespace Client { public partial class Form1 : Form { Socket server; public Form1() { InitializeComponent(); } private void btnConnect_Click(object sender, EventArgs e) { IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ipep); btnConnect.Enabled = false; btnDisconnect.Enabled = true; byte[] data = new byte[1024]; int recv = server.Receive(data); string stringData = Encoding.ASCII.GetString(data, 0, recv); listStatus.Items.Add(stringData); } catch { MessageBox.Show("Unable to connect to server", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void btnSend_Click(object sender, EventArgs e) { int retry = 0; string thongTinSV = txtMaSo.Text + ";" + txtHoTen.Text + ";" + txtNgaySinh.Text + ";" + txtQueQuan.Text; txtMaSo.Clear(); txtHoTen.Clear(); txtNgaySinh.Clear(); txtQueQuan.Clear(); while (retry < 2) { server.Send(Encoding.ASCII.GetBytes(thongTinSV)); byte[] data = new byte[1024]; int recv = server.Receive(data); if (recv > 0) { listStatus.Items.Add("Sent Sinh Vien success:"); listStatus.Items.Add("**********************"); string stringData = Encoding.ASCII.GetString(data, 0, recv); //tach thong tin Sinh Vien phan cach boi dau ; gan vao mang info string[] info = stringData.Split(';'); listStatus.Items.Add("Ma So: " + info[0]);

} else } }

listStatus.Items.Add("Ho Ten: " + info[1]); listStatus.Items.Add("Ngay Sinh: " + info[2]); listStatus.Items.Add("Que Quan: " + info[3]); listStatus.Items.Add("**********************"); break; retry++;

SERVER using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Collections; using System.Net.Sockets; using System.Threading;

private void btnDisconnect_Click(object sender, EventArgs e) { btnConnect.Enabled = true; btnDisconnect.Enabled = false; server.Send(Encoding.ASCII.GetBytes("exit")); listStatus.Items.Add("Disconnected from server"); listStatus.Items.Add("**********************"); } }}

namespace Server { class Program { static ArrayList clientList = new ArrayList();//1 mang chua cac clientsocket static void ReceiveData() { int recv; byte[] data; string[] info; string message; IPEndPoint ipep; ArrayList copyList; while (true) { if (clientList.Count != 0) { copyList = new ArrayList(clientList); //add cac client moi gui message vao copyList Socket.Select(copyList, null, null, 10000000); foreach (Socket client in copyList) { data = new byte[1024]; recv = client.Receive(data); message = Encoding.ASCII.GetString(data, 0, recv); if (message != "exit") { //tach thong tin Sinh Vien phan cach boi dau ; gan vao mang info info = message.Split(';'); ipep = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Receive Sinh Vien from Client {0}", ipep.ToString()); Console.WriteLine("Ma So: " + info[0]); Console.WriteLine("Ho Ten: " + info[1]); Console.WriteLine("Ngay Sinh: " + info[2]); Console.WriteLine("Que Quan: " + info[3]);

client.Send(data, recv, SocketFlags.None); } else//client dissconnect { ipep = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Client {0} disconnected.", ipep.ToString()); clientList.Remove(client); client.Close(); } } } } } public static void Main() { bool found; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Console.WriteLine("Waiting for a client..."); //tao va start 1 luong Thread newThread = new Thread(new ThreadStart(ReceiveData)); newThread.Start(); while (true) { Socket client = newsock.Accept(); IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0}:{1}", clientep.Address, clientep.Port); client.Send(Encoding.ASCII.GetBytes("Connected to Server")); found = false; //kiem tra xem client moi ket noi da co trong clientList chua foreach (Socket sock in clientList) { if (sock.Equals(client)) { found = true; break; } } //neu chua co thi add vao clientList if (!found) clientList.Add(client); } } } }

CHAT TCP PRIVATE


using using using using using using using System; System.Collections.Generic; System.Text; System.Net; System.Collections; System.Net.Sockets; System.Threading;

namespace PrivateChatTCPServer { class Program { static ArrayList clientList = new ArrayList();//1 mang chua cac clientsocket static ArrayList accountList = new ArrayList();//1 mang chua thong tin cac client static void ReceiveData() { int recv; byte[] data; string[] strArr; string strData, message, address, port;

IPEndPoint ipep; ArrayList copyList; while (true) { if (clientList.Count != 0) { copyList = new ArrayList(clientList); //add cac client moi gui message vao copyList Socket.Select(copyList, null, null, 10000000); foreach (Socket client in copyList) { data = new byte[1024]; recv = client.Receive(data); strData = Encoding.ASCII.GetString(data, 0, recv); if (strData != "exit") { strArr = strData.Split('*'); message = strArr[0]; address = strArr[1]; port = strArr[2]; ipep = new IPEndPoint(IPAddress.Parse(address), Int16.Parse(port)); //gui message toi client dich foreach (Socket sock in clientList) { if (sock.RemoteEndPoint.Equals(ipep)) sock.Send(Encoding.ASCII.GetBytes(message)); } } else//client disconnect { ipep = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Client {0} disconnected.", ipep.ToString()); clientList.Remove(client); foreach (Account acc in accountList) { if (client.RemoteEndPoint.Equals(acc.EndPoint)) { accountList.Remove(acc); break; } } client.Close(); //cap nhat thong tin client cho cac client updateClient(clientList, accountList); } } } } } static void Main() { int recv; bool found; byte[] data; Account user; string nickName; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Console.WriteLine("Waiting for a client..."); //tao va start 1 luong Thread newThread = new Thread(new ThreadStart(ReceiveData)); newThread.Start(); while (true) {

Socket client = newsock.Accept(); IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint; data = new byte[1024]; recv = client.Receive(data); nickName = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("{0} connected with {1}:{2}", nickName, clientep.Address, clientep.Port); found = false; //kiem tra xem client moi ket noi da co trong clientList chua foreach (Socket sock in clientList) { if (sock.Equals(client)) { found = true; break; } } //neu chua co thi add vao clientList if (!found) { user = new Account(); user.NickName = nickName; user.EndPoint = clientep; clientList.Add(client); accountList.Add(user); //cap nhat thong tin client cho cac client updateClient(clientList, accountList); } } } static void updateClient(ArrayList clientList, ArrayList accountList) { IPEndPoint endPoint; string address, port, userInfo; string userList = "*"; //tap hop thong tin client dang ket noi foreach (Account acc in accountList) { endPoint = (IPEndPoint)acc.EndPoint; address = endPoint.Address.ToString(); port = endPoint.Port.ToString(); userInfo = acc.NickName + " " + address + " " + port; userList += userInfo + "*"; } //gui danh sach tat ca client da ket noi den tung client foreach (Socket sock in clientList) sock.Send(Encoding.ASCII.GetBytes(userList)); } } //dat class nay o duoi class Program //tao 1 lop Account chua ten nick va endpoint cua client class Account { public string NickName; public IPEndPoint EndPoint; public Account() { NickName = null; EndPoint = null; } }

CLIENT
using System; using System.Collections.Generic; using System.ComponentModel;

using using using using using using using

System.Data; System.Drawing; System.Text; System.Collections; System.Windows.Forms; System.Net; System.Net.Sockets;

namespace PrivateChatTCPClient { public partial class Form1 : Form { int size = 1024; Socket server; bool connect = true; string nickName; byte[] dataRecv = new byte[1024]; ArrayList accountList; public Form1() { InitializeComponent(); } void SendData(IAsyncResult iar) { Socket remote = (Socket)iar.AsyncState; int sent = remote.EndSend(iar); } void ReceiveData(IAsyncResult iar) { if (connect) { Socket remote = (Socket)iar.AsyncState; int recv = remote.EndReceive(iar); string message = Encoding.ASCII.GetString(dataRecv, 0, recv); if (message.Substring(0, 1) != "*") listMessage.Items.Add(message); else//cap nhat friend list { Account account; IPEndPoint ipep; accountList = new ArrayList(); string[] info; //tach thong tin client tu server gui toi luu vao mang clientInfo string[] clientInfo = message.Split('*'); //duyet mang clientInfo, tach thong tin tung client: nickname, address, port //luu vao bien doi tuong account sau do luu bien account vao clientList foreach (string str in clientInfo) { if (str != "") { info = str.Split(' '); ipep = new IPEndPoint(IPAddress.Parse(info[1]), Int16.Parse(info[2])); account = new Account(); account.NickName = info[0]; account.EndPoint = ipep; accountList.Add(account); } } //duyet accountList, add danh sach client vao combobox cmbFriends.Items.Clear(); foreach (Account acc in accountList) {

if (acc.NickName != nickName) cmbFriends.Items.Add(acc.NickName); } } //goi lai phuong thuc ReceiveData de cho nhan du lieu remote.BeginReceive(dataRecv, 0, size, SocketFlags.None,new AsyncCallback(ReceiveData), remote); } } private void btnConnect_Click(object sender, EventArgs e) { if (txtNickName.Text.Trim() != "") { IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ipep); listMessage.Items.Add("Connected to Server"); btnConnect.Enabled = false; btnDisconnect.Enabled = true; nickName = txtNickName.Text.Trim(); byte[] dataSend = Encoding.ASCII.GetBytes(nickName); server.BeginSend(dataSend, 0, dataSend.Length, SocketFlags.None, new AsyncCallback(SendData), server); //goi phuong thuc ReceiveData de cho nhan du lieu server.BeginReceive(dataRecv, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), server); } catch { MessageBox.Show("Unable to connect to server", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } else { txtNickName.Focus(); MessageBox.Show("Please enter your Nick Name", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void btnSend_Click(object sender, EventArgs e) { if (cmbFriends.SelectedIndex != -1) { if (txtMessage.Text.Trim() != "") { //gui message den client duoc chon trong combobox foreach (Account acc in accountList) { if (acc.NickName == cmbFriends.SelectedItem.ToString()) { IPEndPoint ipep = (IPEndPoint)acc.EndPoint; byte[] dataSend = Encoding.ASCII.GetBytes(nickName + ": " + txtMessage.Text.Trim() + "*" + ipep.Address + "*" + ipep.Port); server.BeginSend(dataSend, 0, dataSend.Length, SocketFlags.None, new AsyncCallback(SendData), server); listMessage.Items.Add(nickName + ": " + txtMessage.Text.Trim()); txtMessage.Clear(); txtMessage.Focus(); break; }

} else {

} } else

txtMessage.Focus(); MessageBox.Show("Please enter a message", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

MessageBox.Show("Please choose your friend", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void btnDisconnect_Click(object sender, EventArgs e) { btnConnect.Enabled = true; btnDisconnect.Enabled = false; cmbFriends.Items.Clear(); byte[] dataSend = Encoding.ASCII.GetBytes("exit"); server.BeginSend(dataSend, 0, dataSend.Length, SocketFlags.None, new AsyncCallback(SendData), server); listMessage.Items.Add("Disconnected from server"); connect = false; }

} //dat class nay o duoi class Program //tao 1 lop Account chua ten nick va endpoint cua client class Account { public string NickName; public IPEndPoint EndPoint; public Account() { NickName = null; EndPoint = null; } }} CHAT TCP PUBLIC using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Collections; using System.Threading;

namespace PublicChatTCPServer { class Program { static ArrayList clientList = new ArrayList();//1 mang chua cac clientsocket static void ReceiveData() { int recv; byte[] data; string message; IPEndPoint ipep; ArrayList copyList; while (true) { if (clientList.Count != 0) { copyList = new ArrayList(clientList); //add cac client moi gui message vao copyList

Socket.Select(copyList, null, null, 10000000); foreach (Socket client in copyList) { data = new byte[1024]; recv = client.Receive(data); message = Encoding.ASCII.GetString(data, 0, recv); if (message != "exit") { //gui message toi cac client con lai foreach (Socket sock in clientList) { if (!sock.Equals(client)) sock.Send(data, recv, SocketFlags.None); } } else//client dissconnect { ipep = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Client {0} disconnected.", ipep.ToString()); clientList.Remove(client); client.Close(); } } } } } static void Main() { bool found; IPEndPoint ipep = new IPEndPoint(IPAddress.Any,9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Console.WriteLine("Waiting for a client..."); //tao va start 1 luong Thread newThread = new Thread(new ThreadStart(ReceiveData)); newThread.Start(); while (true) { Socket client = newsock.Accept(); IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0}:{1}", clientep.Address, clientep.Port); client.Send(Encoding.ASCII.GetBytes("Connected to Server")); found = false; //kiem tra xem client moi ket noi da co trong clientList chua foreach (Socket sock in clientList) { if (sock.Equals(client)) { found = true; break; } } //neu chua co thi add vao clientList if (!found) clientList.Add(client); } } } }

CLIENT
using using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms; System.Net;

using System.Net.Sockets; using System.Threading; namespace PublicChatTCPClient { public partial class Form1 : Form { int size = 1024; Socket server; bool connect = true; string nickName; byte[] dataRecv = new byte[1024]; public Form1() { InitializeComponent(); } void SendData(IAsyncResult iar) { Socket remote = (Socket)iar.AsyncState; int sent = remote.EndSend(iar); } void ReceiveData(IAsyncResult iar) { if (connect) { Socket remote = (Socket)iar.AsyncState; int recv = remote.EndReceive(iar); string message = Encoding.ASCII.GetString(dataRecv, 0, recv); listMessage.Items.Add(message); //goi lai phuong thuc ReceiveData de cho nhan du lieu remote.BeginReceive(dataRecv, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), remote); } } private void btn_Connect_Click(object sender, EventArgs e) { if (txtNickName.Text.Trim() != "") { IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ipep); btn_Connect.Enabled = false; btn_Disconnect.Enabled = true; nickName = txtNickName.Text.Trim(); //goi phuong thuc ReceiveData de cho nhan du lieu server.BeginReceive(dataRecv, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), server); } catch { MessageBox.Show("Unable to connect to server", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } else { txtNickName.Focus();

MessageBox.Show("Please enter your Nick Name", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } }

private void btn_Send_Click(object sender, EventArgs e) { if (txtMessage.Text != "") { listMessage.Items.Add(nickName + ": " + txtMessage.Text.Trim()); byte[] dataSend = Encoding.ASCII.GetBytes(nickName + ": " + txtMessage.Text.Trim()); server.BeginSend(dataSend, 0, dataSend.Length, SocketFlags.None, new AsyncCallback(SendData), server); txtMessage.Clear(); txtMessage.Focus(); } else { txtMessage.Focus(); MessageBox.Show("Please enter a message", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void btn_Disconnect_Click(object sender, EventArgs e) { btn_Connect.Enabled = true; btn_Disconnect.Enabled = false; byte[] dataSend = Encoding.ASCII.GetBytes("exit"); server.BeginSend(dataSend, 0, dataSend.Length, SocketFlags.None, new AsyncCallback(SendData), server); listMessage.Items.Add("Disconnected from server"); connect = false; } } } CHAT UDP SERVER using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Collections; using System.Net.Sockets; namespace PrivateChat_UDPServer { class Server { public static void Main() { int recv; bool found; string stringData, stringData2; Account user; ArrayList accountList = new ArrayList(); byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); newsock.Bind(ipep); //Ly EndPoint t Client (Ip:Port) IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)(sender); Console.WriteLine("Private Chat Server started");

while (true) { data = new byte[1024]; found = false; recv = newsock.ReceiveFrom(data, ref Remote); stringData = Encoding.ASCII.GetString(data, 0, recv); stringData2 = stringData + " connected"; if (stringData2.Substring(0, 4) != "exit")//client connect { user = new Account(); user.NickName = stringData; user.EndPoint = Remote; //kiem tra client moi gui data toi co nam trong accountList khong foreach (Account acc in accountList) { if (acc.Equals(user)) { found = true; break; } } if (!found)//neu client chua nam trong accountList thi add vao { accountList.Add(user); Console.WriteLine(stringData2 + " at " + Remote.ToString()); newsock.SendTo(Encoding.ASCII.GetBytes("Connected to Server"), Remote); //cap nhat thong tin client cho cac client updateClient(newsock, accountList); } } else//client disconnect { //duyet accountList de xoa thong tin cua client da disconnect foreach (Account acc in accountList) { if (acc.EndPoint.Equals(Remote)) { accountList.Remove(acc); break; } } Console.WriteLine(stringData.Substring(4, stringData.Length - 4) + " disconnected"); //cap nhat thong tin client cho cac client updateClient(newsock, accountList); } } } static void updateClient(Socket newsock, ArrayList accountList) { IPEndPoint endPoint; string address, port, userInfo; string clientList = ""; //tap hop thong tin client dang ket noi foreach (Account acc in accountList) { endPoint = (IPEndPoint)acc.EndPoint; address = endPoint.Address.ToString(); port = endPoint.Port.ToString(); userInfo = acc.NickName + " " + address + " " + port; clientList += userInfo + "*"; } //gui danh sach tat ca client da ket noi den tung client foreach (Account acc in accountList) newsock.SendTo(Encoding.ASCII.GetBytes(clientList), acc.EndPoint); }

} //dat class nay o duoi class Server //tao 1 lop Account chua ten nick va endpoint cua client class Account { public string NickName; public EndPoint EndPoint; public Account() { NickName = null; EndPoint = null; } }}

CLIENT
using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms; System.Net; System.Collections; System.Net.Sockets;

namespace PrivateChat_UDPClient { public partial class Main : Form { Socket server; string nickName; EndPoint Remote; int size = 1024; IPEndPoint ipepServer; byte[] dataRecv = new byte[1024]; ArrayList clientList; public Main() { InitializeComponent(); } void SendData(IAsyncResult iar) { Socket sock = (Socket)iar.AsyncState; int sent = sock.EndSendTo(iar); } void ReceiveData(IAsyncResult iar) { Socket sock = (Socket)iar.AsyncState; int recv = sock.EndReceiveFrom(iar, ref Remote); string stringData = Encoding.ASCII.GetString(dataRecv, 0, recv); if (Remote.Equals(ipepServer))//neu data tu server gui den { if (stringData == "Connected to Server") listMessage.Items.Add(stringData); else { Account account; IPEndPoint endPoint; clientList = new ArrayList(); string[] info; //tach thong tin client tu server gui toi luu vao mang clientInfo string[] clientInfo = stringData.Split('*');

port

//duyet mang clientInfo, tach thong tin tung client: nickname, address,

//luu vao bien doi tuong account sau do luu bien account vao clientList foreach (string str in clientInfo) { if (str != "") { info = str.Split(' '); endPoint = new IPEndPoint(IPAddress.Parse(info[1]), Int16.Parse(info[2])); account = new Account(); account.NickName = info[0]; account.EndPoint = endPoint; clientList.Add(account); } } //duyet clientList, add danh sach client vao combobox cmbFriends.Items.Clear(); foreach (Account acc in clientList) { if (acc.NickName != nickName) cmbFriends.Items.Add(acc.NickName); } } } else//data tu client khac gui den listMessage.Items.Add(stringData); //goi lai phuong thuc ReceiveData de cho nhan du lieu sock.BeginReceiveFrom(dataRecv, 0, size, SocketFlags.None, ref Remote, new AsyncCallback(ReceiveData), sock); } private void btnConnect_Click(object sender, EventArgs e) { if (txtNickName.Text.Trim() != "") { btnConnect.Enabled = false; btnDisconnect.Enabled = true; nickName = txtNickName.Text.Trim(); ipepServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint EPsender = new IPEndPoint(IPAddress.Any, 0); Remote = (EndPoint)EPsender; byte[] dataSend = Encoding.ASCII.GetBytes(nickName); server.BeginSendTo(dataSend, 0, dataSend.Length, SocketFlags.None, ipepServer, new AsyncCallback(SendData), server); //goi phuong thuc ReceiveData de cho nhan du lieu try { server.BeginReceiveFrom(dataRecv, 0, size, SocketFlags.None, ref Remote, new AsyncCallback(ReceiveData), server); } catch { MessageBox.Show("Can't connect to Server", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { txtNickName.Focus(); MessageBox.Show("Please enter your Nick Name", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

private void btnSend_Click(object sender, EventArgs e) { if (cmbFriends.SelectedIndex != -1) { if (txtMessage.Text.Trim() != "") { //gui message den client duoc chon trong combobox foreach (Account acc in clientList) { if (acc.NickName == cmbFriends.SelectedItem.ToString()) { EndPoint endPoint = acc.EndPoint; byte[] dataSend = Encoding.ASCII.GetBytes(nickName + ": " + txtMessage.Text.Trim()); server.BeginSendTo(dataSend, 0, dataSend.Length, SocketFlags.None, endPoint, new AsyncCallback(SendData), server); listMessage.Items.Add(nickName + ": " + txtMessage.Text.Trim()); txtMessage.Clear(); txtMessage.Focus(); break; } } } else { txtMessage.Focus(); MessageBox.Show("Please enter a message", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else MessageBox.Show("Please choose your friend", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void btnDisconnect_Click(object sender, EventArgs e) { btnConnect.Enabled = true; btnDisconnect.Enabled = false; cmbFriends.Items.Clear(); byte[] dataSend = Encoding.ASCII.GetBytes("exit" + nickName); server.BeginSendTo(dataSend, 0, dataSend.Length, SocketFlags.None, ipepServer, new AsyncCallback(SendData), server); listMessage.Items.Add("Disconnect from Server"); }

} //dat class nay o duoi class Main //tao 1 lop Account chua ten nick va endpoint cua client class Account { public string NickName; public EndPoint EndPoint; public Account() { NickName = null; EndPoint = null; } }} PUBLIC CHAT UDP SERVER

using System; using System.Collections.Generic; using System.Text;

using System.Net; using System.Collections; using System.Net.Sockets; namespace PublicChat_UDPServer { class Server { public static void Main() { int recv; byte[] data = new byte[1024]; bool found; string stringData; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); newsock.Bind(ipep); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)(sender); ArrayList EndPointList = new ArrayList(); Console.WriteLine("Public Chat Server started"); while (true) { data = new byte[1024]; recv = newsock.ReceiveFrom(data, ref Remote); stringData = Encoding.ASCII.GetString(data, 0, recv); if (stringData.Substring(0, 4) != "exit") { found = false; //kiem tra xem endpoint trong remote da co trong EndPointList chua foreach (EndPoint ep in EndPointList) { if (ep.Equals(Remote)) { found = true; break; } } //neu chua co thi add vao list if (!found) { EndPointList.Add(Remote); Console.WriteLine(stringData + " at " + Remote.ToString()); newsock.SendTo(Encoding.ASCII.GetBytes("Connected to Server"), Remote); } //duyet list de gui data toi tung endpoint trong list foreach (EndPoint ep in EndPointList) if (!ep.Equals(Remote)) newsock.SendTo(data, data.Length, SocketFlags.None, ep); } else//client disconnect { //duyet EndPointList de xoa endpoint cua client da disconnect foreach (EndPoint ep in EndPointList)

{ if (ep.Equals(Remote)) { EndPointList.Remove(ep); break; } } stringData = stringData.Substring(4, stringData.Length - 4) + " disconnected"; Console.WriteLine(stringData); data = Encoding.ASCII.GetBytes(stringData); //gui thong tin client disconnect den cac client con lai foreach (EndPoint ep in EndPointList) newsock.SendTo(data, data.Length, SocketFlags.None, ep); } } } }} CLIENT 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; using System.Net.Sockets; namespace PublicChat_UDPClient { public partial class Client : Form { Socket server; string nickName; EndPoint Remote; IPEndPoint ipep; int size = 1024; byte[] dataRecv = new byte[1024]; public Client() { InitializeComponent(); } void SendData(IAsyncResult iar) { Socket sock = (Socket)iar.AsyncState; int sent = sock.EndSendTo(iar); } void ReceiveData(IAsyncResult iar) { Socket sock = (Socket)iar.AsyncState; int recv = sock.EndReceiveFrom(iar, ref Remote); string stringData = Encoding.ASCII.GetString(dataRecv, 0, recv); listMessage.Items.Add(stringData); //goi lai phuong thuc ReceiveData de cho nhan du lieu sock.BeginReceiveFrom(dataRecv, 0, size, SocketFlags.None, ref Remote, new AsyncCallback(ReceiveData), sock); } private void btn_Connect_Click(object sender, EventArgs e)

{ if (txtNickName.Text.Trim() != "") { btn_Connect.Enabled = false; btn_Disconnect.Enabled = true; nickName = txtNickName.Text.Trim(); ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint EPsender = new IPEndPoint(IPAddress.Any, 0); Remote = (EndPoint)EPsender; byte[] dataSend = Encoding.ASCII.GetBytes(nickName + " connected"); server.BeginSendTo(dataSend, 0, dataSend.Length, SocketFlags.None, ipep, new AsyncCallback(SendData), server); //goi phuong thuc ReceiveData de cho nhan du lieu try { server.BeginReceiveFrom(dataRecv, 0, size, SocketFlags.None, ref Remote, new AsyncCallback(ReceiveData), server); } catch { MessageBox.Show("Can't connect to Server", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { txtNickName.Focus(); MessageBox.Show("Please enter your Nick Name", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void btn_Send_Click(object sender, EventArgs e) { if (txtMessage.Text.Trim() != "") { listMessage.Items.Add(nickName + ": " + txtMessage.Text.Trim()); byte[] dataSend = Encoding.ASCII.GetBytes(nickName + ": " + txtMessage.Text.Trim()); server.BeginSendTo(dataSend, 0, dataSend.Length, SocketFlags.None, ipep, new AsyncCallback(SendData), server); txtMessage.Clear(); } else { txtMessage.Focus(); MessageBox.Show("Please enter a message", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void btn_Disconnect_Click(object sender, EventArgs e) { btn_Connect.Enabled = true; btn_Disconnect.Enabled = false; byte[] dataSend = Encoding.ASCII.GetBytes("exit" + nickName); server.BeginSendTo(dataSend, 0, dataSend.Length, SocketFlags.None, ipep, new AsyncCallback(SendData), server);

listMessage.Items.Add("Disconnect from Server"); } }

You might also like