Lập trình UDP socket giao tiếp client server

27 1K 1
Lập trình UDP socket giao tiếp client server

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Lập trình UDP socket giao tiếp client server

Đại Học Bách Khoa Hà Nội Viện Điện tử viễn thông -o0o - BÁO CÁO BÀI TẬP LỚN Kỹ thuật mạng nâng cao Đề tài : Lập trình UDP socket giao tiếp Client Server Giảng viên hướng dẫn: Sinh viên thực : Nguyễn Thế Hưng Phạm Thu Hường Nguyễn Ngọc Kiều ĐT8 - K52 Hà Nội, tháng 10 năm 2011 20071475 Mục lục Contents Contents Yêu cầu đề tài: Tạo chương trình Client-Server trao đổi thông tin qua UDP socket thực chức sau : - Client sau kết nối gửi tới server thông tin địa Mac client - Server sau nhận thông tin kiểm tra thông tin client ghi vào file hay chưa, chưa lưu vào file Sau gửi lại client tin xác nhận nhận, ghi, có thông tin - Server lưu giữ thông tin client kết nối vào server.Client muốn ngắt kết nối cần gửi tin thông báo cho server - Khi có client khác kết nối vào server, server gửi cho client khác thông tin client kết nối vào.Client nhận tin hiển thị thông tin mac client kết nối vào server I Các kiến thức máy tính Họ giao thức TCP/IP Hình 1-3: Các tầng giao thức TCP/IP so với cấc tầng mô hình OSI Application: Xác nhận quyền, nén liệu dịch vụ cho người dùng Transport: Xử lý liệu hệ thống va cung cấp việc truy cập mạng cho ứng dụng Network: Tìm ñường cho packet Link: Mức OS thiết bị giao tiếp mạng máy tính Một số điểm khác TCP/IP mô hình OSI + Lớp ứng dụng TCP/IP xử lý chức lớp 5,6,7 mô hình OSI + Lớp transport TCP/IP cung cấp cớ chế UDP truyền không tin cậy, transport OSI ñảm bảo truyền tin cậy + TCP/IP tập protocols (một giao thức) + TCP/IP xây dựng trước OSI Giao thức UDP a Khái quát UDP (User Datagram Protocol) giao thức cốt lõi giao thức TCP/IP Dùng UDP, chương trình mạng máy tính gởi liệu ngắn gọi datagram tới máy khác UDP không cung cấp tin cậy thứ tự truyền nhận mà TCP làm; gói liệu đến không thứ tự bị mà thông báo Tuy nhiên UDP nhanh hiệu mục tiêu kích thước nhỏ yêu cầu khắt khe thời gian Do chất không trạng thái nên hữu dụng việc trả lời truy vấn nhỏ với số lượng lớn người yêu cầu Những ứng dụng phổ biến sử dụng UDP DNS (Domain Name System), ứng dụng streaming media, Voice over IP, Trivial File Transfer Protocol (TFTP), game trực tuyến b Cổng UDP dùng cổng phép giao tiếp ứng dụng diễn Cổng dùng 16 bit để đánh địa chỉ, số cổng nằm khoản đến 65.535 Cổng để dành không nên sử dụng Cổng từ đến 1023 gọi cổng "well-known" hệ điều hành tựa Unix, việc gắn kết tới cổng đòi hỏi quyền root Cổng 1024 đến 49.151 cổng đăng ký Cổng từ 49.152 đến 65.535 cổng tạm, dùng chủ yếu client liên lạc với server c Cấu trúc gói UDP giao thức hướng thông điệp nhỏ tầng giao vận mô tả RFC 768 IETF Trong giao thức TCP/IP, UDP cung cấp giao diện đơn giản tầng mạng bên (thí dụ, IPv4) tầng phiên làm việc tầng ứng dụng phía UDP không đảm bảo cho tầng phía thông điệp gửi người gửi trạng thái thông điệp UDP gửi (Vì lý UDP gọi Unreliable Datagram Protocol) UDP thêm thông tin multiplexing giao dịch Các loại thông tin tin cậy cho việc truyền liệu cần phải xây dựng tầng cao Phần header UDP chứa trường liệu, có trường tùy chọn (ô đỏ bảng) Source port Trường xác định cổng người gửi thông tin có ý nghĩa muốn nhận thông tin phản hồi từ người nhận Nếu không dùng đến đặt Destination port Trường xác định cổng nhận thông tin, trường cần thiết Length Trường có độ dài 16 bit xác định chiều dài toàn datagram: phần header liệu Chiều dài tối thiểu byte gói tin liệu, có header Trường checksum 16 bit dùng cho việc kiểm tra lỗi phần header liệu Phương pháp tính checksum định nghĩa RFC 768 Do thiếu tính tin cậy, ứng dụng UDP nói chung phải chấp nhận mát, lỗi trùng liệu Một số ứng dụng TFTP có nhu cầu phải thêm kỹ thuật làm tin cậy vào tầng ứng dụng Hầu hết ứng dụng UDP không cần kỹ thuật làm tin cậy bị bỏ Streaming media, game trực tuyến voice over IP (VoIP) thí dụ cho ứng dụng thường dùng UDP Nếu ứng dụng đòi hỏi mức độ cao tính tin cậy, giao thức TCP mã erasure dùng thay Thiếu chế kiểm soát tắc nghẽn kiểm soát luồng, kỹ thuật dựa mạng cần thiết để giảm nguy hiệu ứng tắc nghẽn dây chuyền không kiểm soát, tỷ lệ tải UDP cao Nói cách khác, người gởi gói UDP phát tắc nghẽn, thành phần dựa mạng router dùng hàng đợi gói (packet queueing) kỹ thuật bỏ gói công cụ để giảm tải UDP Giao thức Datagram Congestion Control Protocol (DCCP) thiết kế giải pháp cho vấn đề cách thêm hành vi kiểm soát tắc nghẽn cho thiết bị đầu cuối cho dòng liệu UDP streaming media Mặc dù tổng lượng lưu thông UDP mạng thường vài phần trăm, có nhiều ứng dụng quan trọng dùng UDP, bao gồm DNS, SNMP, DHCP RIP II UDP socket a Socket Socket giao diện lập trình ứng dụng (API) mạng Thông qua giao diện lập trình ñiều khiển việc truyền thông hai máy sử dụng giao thức mức thấp TCP, UDP… Socket trừu tượng hoá mức cao, tưởng tượng thiết bị truyền thông hai chiều gửi - nhận liệu hai máy tính với  Các loại Socket  Socket hướng kết nối (TCP Socket)  Socket không hướng kết nối (UDP Socket)  Raw Socket  ðặc điểm Socket hướng kết nối  Có đường kết nối ảo tiến trình  Một tiến trình phải ñợi tiến trình yêu cầu kết nối  Có thể sử dụng ñể liên lạc theo mô hình Client/Server  Trong mô hình Client/Server Server lắng nghe chấp nhận yêu cầu kết nối  Mỗi thông ñiệp gửi ñều có xác nhận trở  Các gói tin chuyển  đặc điểm Socket không hướng kết nối  Hai tiến trình liên lạc với không kết nối trực tiếp  Thông ñiệp gửi ñi phải kèm theo ñịa người nhận  Thông ñiệp gửi nhiều lần  Người gửi không chắn thông điệp tới tay người nhận  Thông ñiệp gửi sau ñến ñích trước thông ñiệp gửi trước ñó  Số hiệu cổng Socket  để thực giao tiếp, hai trình phải công bố số hiệu cổng socket mà sử dụng  Mỗi cổng giao tiếp thể địa xác định hệ thống Khi trình gán số hiệu cổng, nhận liệu gởi ñến cổng từ trình khác  Quá trình lại yêu cầu tạo socket b Giới thiệu NameSpace System.Net System.Net.Sockets  Cung cấp giao diện lập trình đơn giản cho nhiều giao thức mạng  Có nhiều lớp để lập trình  Ta quan tâm lớp IPAdress, IPEndPoint, DNS, …  Lớp IPAdress  Một số Field cần ý:  Any: Cung cấp ñịa IP ñể Server phải lắng nghe tất Card mạng  Broadcast: Cung cấp ñịa IP quảng bá  Loopback: Trả ñịa IP lặp  AdressFamily: Trả họ ñịa IP hành  Lớp IPAddress  Một số phương thức cần ý:  Phương thức khởi tạo  IPAddress(Byte[])  IPAddress(Int64)  IsLoopback: Cho biết ñịa có phải ñịa lặp không  Parse: Chuyển IP dạng xâu IP chuẩn  ToString: Trả ñịa IP dạng xâu  TryParse: Kiểm tra IP dạng xâu có hợp lệ không?  Lớp IPEndPoint Cổng, ví dụ: 192.168.1.1:8080  Lớp DNS  Một số thành phần lớp:  HostName: Cho biết tên máy ñược phân giải  GetHostAddress: Trả tất IP trạm  GetHostEntry: Giải ñáp tên ñịa truyền vào trả ñối tượng IPHostEntry  GetHostName: Lấy tên máy tính cục  NameSpace System.Net.Sockets  Một số lớp hay dùng: TcpClient, UdpClient, TcpListener, Socket, NetworkStream, …  để tạo Socket  Socket(AddressFamily af, SocketType st, ProtocolType pt) III Lập trình Giao diện a Server • Chưa có client kết nối • Có Client kết nối b Client • Login • Form Chương trình a Server using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Net.NetworkInformation; using System.IO; using System.Text.RegularExpressions; //using System.Data; namespace Server { // lenh dung trao doi giua Server va Client enum Command { Login, //Dang nhap toi Server Logout, //Dang xuat khoi Server ACK, //Thong bao da nhan, ghi, da co thong tin MAC ve Client NewClient, //Gui cho Client thong bao dia chi MAC Client moi ket noi Null, //No command Stop //Server will stop after 5s } public partial class Form1 : Form { // Start receiving data serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender); // Doi text Button1 Stop Server button1.Text = "Stop Server"; toolTip1.SetToolTip(this.button1, "Click to Stop Server "); // tra gia tri flag StartSer ve True fstartSer = true; // enabel nut Stop menu Server stopToolStripMenuItem.Enabled = true; startToolStripMenuItem.Enabled = false; proBar1.Style = ProgressBarStyle.Marquee; changePortNumberToolStripMenuItem.Enabled = false; } catch (Exception ex) { // thong bao loi va Set co FstartServer ve false MessageBox.Show(ex.Message, "ServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error); fstartSer = false; stopToolStripMenuItem.Enabled = false; startToolStripMenuItem.Enabled = true; proBar1.Style = ProgressBarStyle.Blocks; changePortNumberToolStripMenuItem.Enabled = true; } } else { _quiting = true; try { serverSocket.Close(); // Doi text Button1 Start Server button1.Text = "Start Server"; toolTip1.SetToolTip(this.button1, "Click to Start Server "); // Set flag StartSer ve false fstartSer = false; stopToolStripMenuItem.Enabled = false; startToolStripMenuItem.Enabled = true; proBar1.Style = ProgressBarStyle.Blocks; changePortNumberToolStripMenuItem.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message); fstartSer = true; // Doi text Button1 Stop Server button1.Text = "Stop Server"; toolTip1.SetToolTip(this.button1, "Click to Stop Server "); proBar1.Style = ProgressBarStyle.Marquee; // tra gia tri flag StartSer ve True fstartSer = true; // menu Server stopToolStripMenuItem.Enabled = true; startToolStripMenuItem.Enabled = false; changePortNumberToolStripMenuItem.Enabled = false; } } } // ham OnReceive duoc goi sau ket thuc nhan du lieu tu Client private void OnReceive(IAsyncResult ar) { bool have = false; try { // bat loi Stop server o day => tham khao tren mang IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0); EndPoint epSender = (EndPoint)ipeSender; try { serverSocket.EndReceiveFrom(ar, ref epSender); } catch (ObjectDisposedException) { if (_quiting) return; throw; } //convert byteData to msgReceived Data msgReceived = new Data(byteData); //We will send this object in response the users request Data msgToSend = new Data(); byte[] message; //If the message is to login, logout, or simple text message //then when send to others the type of the message remains the same msgToSend.cmdCommand = msgReceived.cmdCommand; msgToSend.strMac = msgReceived.strMac; msgToSend.strIP = msgReceived.strIP; int nIndex = 0; switch (msgReceived.cmdCommand) { case Command.Login: //When a user logs in to the server then we add her to our //list of clients ClientInfo clientInfo = new ClientInfo(); clientInfo.endpoint = epSender; clientInfo.strMac = msgReceived.strMac; clientInfo.strIP = msgReceived.strIP; foreach (ClientInfo client in clientOld) { if ((client.strMac == msgReceived.strMac)&&(client.strIP == msgReceived.strIP)) { have = true; break; } //++nIndex; } clientList.Add(clientInfo); // ghi file neu chua co client moi if (!have) { StringBuilder sb = new StringBuilder(); sb.AppendLine(msgReceived.strIP + "#" + msgReceived.strMac); using (StreamWriter outfile = new StreamWriter("server.txt", true)) { outfile.Write(sb.ToString()); } } // gui ACK toi client thong bao da nhan dc msgToSend.cmdCommand = Command.ACK; message = msgToSend.ToByte(); serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender, new AsyncCallback(OnSend), epSender); _changeView = true; break; case Command.Logout: //When a user wants to log out of the server then we search for her //in the list of clients and close the corresponding connection nIndex = 0; foreach (ClientInfo client in clientList) { if (client.strMac == msgReceived.strMac) { clientList.RemoveAt(nIndex); break; } ++nIndex; } toolStripStatusLabel1.Text = "Client " + msgReceived.strIP + " with Mac add : " + msgReceived.strMac + " logout"; _changeView = true; break; default: break; } // if (msgReceived.cmdCommand == Command.Login) { msgToSend.cmdCommand = Command.NewClient; message = msgToSend.ToByte(); foreach (ClientInfo clientInfo in clientList) { // //if (clientInfo.endpoint != epSender) { //Gui Mac cho cac Client cu biet co client moi serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint, new AsyncCallback(OnSend), clientInfo.endpoint); } } //if (!have) toolStripStatusLabel1.Text = "Client " + msgReceived.strIP + " with Mac add : " + msgReceived.strMac + " login"; } ipeSender = new IPEndPoint(IPAddress.Any, 0); epSender = (EndPoint)ipeSender; serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender); //} } catch (Exception ex) { MessageBox.Show(ex.Message, "ServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void OnSend(IAsyncResult ar) { try { serverSocket.EndSend(ar); } catch (Exception ex) { MessageBox.Show(ex.Message, "ServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void timer1_Tick(object sender, EventArgs e) { this.Text = DateTime.Now.ToString(); } private void changePortNumberToolStripMenuItem_Click(object sender, EventArgs e) { int p = _Port; if (InputBox("ServerUDP", "Port number to listening", ref p) == DialogResult.OK) { if ((p != 8888) && (p > 1022) && (p < 65536)) { _Port = p; txtPort.Text = _Port.ToString(); } else { if (MessageBox.Show("Port number incorrect !", "ServerUDP", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry) { changePortNumberToolStripMenuItem_Click(sender, e); } else { MessageBox.Show("Fail to change Port number Default Port number is 8888", "ServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Warning); _Port = 8888; txtPort.Text = "8888"; } } } else { MessageBox.Show("No change Port number", "ServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Information); } txtPort.Focus(); //Regex rex = new Regex(@"^[a-zA-Z]\w{1,39}$"); // kiem tra dau vao //if (!(rex.Match(server)).Success) //cau lenh tren nghia la khong nam tap 0-9 } public static DialogResult InputBox(string title, string promptText, ref int value) { Form form = new Form(); Label label = new Label(); TextBox textBox = new TextBox(); Button buttonOk = new Button(); Button buttonCancel = new Button(); form.Text = title; label.Text = promptText; textBox.Text = value.ToString(); textBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; buttonOk.Text = "OK"; buttonCancel.Text = "Cancel"; buttonOk.DialogResult = DialogResult.OK; buttonCancel.DialogResult = DialogResult.Cancel; label.SetBounds(9, 20, 100, 13); textBox.SetBounds(12, 36, 75, 20); buttonOk.SetBounds(12, 60, 75, 23); buttonCancel.SetBounds(93, 60, 75, 23); label.AutoSize = true; textBox.Anchor = textBox.Anchor | AnchorStyles.Right; //buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; //buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; form.ClientSize = new Size(150, 107); form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel }); form.ClientSize = new Size(Math.Max(150, label.Right + 40), form.ClientSize.Height); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.StartPosition = FormStartPosition.CenterScreen; form.ControlBox = false; form.AcceptButton = buttonOk; form.CancelButton = buttonCancel; DialogResult dialogResult = form.ShowDialog(); //Regex rex = new Regex(@"^[0-9]\w{3,4}$"); try { value = Convert.ToInt32(textBox.Text); } catch (Exception ex) { MessageBox.Show(ex.Message); } return dialogResult; } private void startToolStripMenuItem_Click(object sender, EventArgs e) { button1_Click(sender, e); } private void stopToolStripMenuItem_Click(object sender, EventArgs e) { button1_Click(sender, e); } private void exitApplicationToolStripMenuItem_Click(object sender, EventArgs e) { if (fstartSer == true) { _quiting = true; try { serverSocket.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } Application.Exit(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { //Thoát khỏi form chuỗi xác nhận với biểu tượng cảnh báo if (MessageBox.Show("Bạn có chắn thoát khỏi chương trình ?", "Thông Báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Cancel) { e.Cancel = true; } } private void Form1_Load(object sender, EventArgs e) { clientConnectingToolStripMenuItem.Enabled = false; clientConnectingToolStripMenuItem.Checked = true; proBar1.Step = 1; } private void clientConnectedToolStripMenuItem_Click(object sender, EventArgs e) { /* try { // Create an instance of StreamReader to read from a file // The using statement also closes the StreamReader using (StreamReader sr = new StreamReader("server.txt")) { String line = ""; StreamReader reader = new StreamReader("server.txt"); // Read and display lines from the file until the end of // the file is reached { line = line + reader.ReadLine() + "\r\n"; } while (reader.Peek() != -1); textBox1.Text = line; reader.Close(); } } catch (Exception exx) { MessageBox.Show(exx.Message); } */ try { timer2.Enabled = false; String line = ""; string sIP, sMac; StreamReader reader = new StreamReader("server.txt"); // Read and display lines from the file until the end of // the file is reached int count = 1; dataGridView1.Rows.Clear(); { line = reader.ReadLine(); sIP = line.Substring(0, line.IndexOf("#")); sMac = line.Substring(line.IndexOf("#") + 1, line.Length - line.IndexOf("#") - 1); dataGridView1.Rows.Add(count, sIP, sMac); count++; } while (reader.Peek() != -1); reader.Close(); clientConnectedToolStripMenuItem.Enabled = false; clientConnectingToolStripMenuItem.Enabled = true; clientConnectingToolStripMenuItem.Checked = false; } catch (Exception eh) { MessageBox.Show(eh.Message, "SERVER_UDP", MessageBoxButtons.OK,MessageBoxIcon.Error); clientConnectedToolStripMenuItem.Enabled = true; clientConnectingToolStripMenuItem.Enabled = false; clientConnectingToolStripMenuItem.Checked = true; } } private void timer2_Tick(object sender, EventArgs e) { if (_changeView) { dataGridView1.Rows.Clear(); int count = 1; foreach (ClientInfo tt in clientList) { dataGridView1.Rows.Add(count, tt.strIP, tt.strMac); count++; } _changeView = false; } } private void clientConnectingToolStripMenuItem_Click(object sender, EventArgs e) { clientConnectedToolStripMenuItem.Enabled = true; clientConnectedToolStripMenuItem.Checked = false; clientConnectingToolStripMenuItem.Enabled = false; _changeView = true; timer2.Enabled = true; } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Version 1.0\nNguyễn Thế Hưng\nPhạm Thu Hường\nNguyễn Ngọc Kiều","Kỹ thuật mạng nâng cao", MessageBoxButtons.OK); } private void settingToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Nothing", "SERVER_UDP", MessageBoxButtons.OK); } private void load_old() { clientOld = new ArrayList(); String line = ""; string sIP, sMac; if (File.Exists("server.txt")) { StreamReader reader = new StreamReader("server.txt"); // Read and display lines from the file until the end of // the file is reached { line = reader.ReadLine(); //if (line[0] == 35)// dau thang sIP = line.Substring(0, line.IndexOf("#")); sMac = line.Substring(line.IndexOf("#") + 1, line.Length - line.IndexOf("#") - 1); ClientInfo temp = new ClientInfo(); temp.strIP = sIP; temp.strMac = sMac; temp.endpoint = null; clientOld.Add(temp); } while (reader.Peek() != -1); reader.Close(); } } } } b Client using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; // using System.Net.NetworkInformation; namespace Client { public partial class Login : Form { [System.Runtime.InteropServices.DllImport("iphlpapi.dll", ExactSpelling = true)] static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref int PhyAddrLen); public Socket clientSocket; public EndPoint epServer; public string strMac, strIP; private byte[] byteData; private int count; public Login() { InitializeComponent(); } private void btnCancel_Click(object sender, EventArgs e) { Close(); } private void Login_Load(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false; btnOK.Enabled = false; timer1.Enabled = false; txtIPserver.Text = ""; txtPort.Text = "8888"; } private void btnOK_Click(object sender, EventArgs e) { //if ((textBox1.Text == "huong") && (textBox2.Text == "bkacad")) { try { // su dung UDP socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //IP address cua Server IPAddress IPserver = IPAddress.Parse(txtIPserver.Text); // lay port server lang nghe IPEndPoint ipEndPoint = new IPEndPoint(IPserver, Convert.ToInt32(txtPort.Text)); epServer = (EndPoint)ipEndPoint; // du lieu gui di Data msgToSend = new Data(); msgToSend.cmdCommand = Command.Login; // lay dia chi card mang va MAC UdpClient u = new UdpClient(txtIPserver.Text, 1); IPAddress localAddr = ((IPEndPoint)u.Client.LocalEndPoint).Address; msgToSend.strIP = localAddr.ToString(); msgToSend.strMac = GetMacAddress(localAddr).ToString(); // bien truyen cho form1 strMac = msgToSend.strMac; strIP = msgToSend.strIP; //Convert sang Byte byteData = msgToSend.ToByte(); //login to Server clientSocket.BeginSendTo(byteData, 0, byteData.Length, SocketFlags.None, epServer, new AsyncCallback(OnSend), null); //chuan bi bien luu tru thong tin tra ve byteData = new byte[1024]; //Start listening to the data asynchronously count = 0; // btnOK.Enabled = false; btnCancel.Enabled = false; timer1.Enabled = true; // san sang nhan du lieu clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null); } catch (SocketException) { timer1.Enabled = false; MessageBox.Show("Server is not running or Port number is incorrect !!!", "Client", MessageBoxButtons.OK, MessageBoxIcon.Error); // btnCancel.Enabled = true; } catch (Exception ex1) { timer1.Enabled = false; MessageBox.Show(ex1.Message, "Client1", MessageBoxButtons.OK, MessageBoxIcon.Error); // btnCancel.Enabled = true; } } //else //{ //MessageBox.Show("Dang nhap that bai","SERVERUDP"); //} } private void OnSend(IAsyncResult ar) { try { clientSocket.EndSend(ar); } catch (Exception ex) { MessageBox.Show(ex.Message, "Client", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void OnReceive(IAsyncResult ar) { try { clientSocket.EndReceive(ar); //Convert the bytes received into an object of type Data Data msgReceived = new Data(byteData); //Accordingly process the message received switch (msgReceived.cmdCommand) { case Command.ACK: timer1.Enabled = false; DialogResult = DialogResult.OK; Close(); break; default: break; } } catch (ObjectDisposedException) {} catch (Exception ex) { MessageBox.Show(ex.Message, "Client", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public static PhysicalAddress GetMacAddress(IPAddress ipAddress) { const int MacAddressLength = 6; int length = MacAddressLength; var macBytes = new byte[MacAddressLength]; SendARP(BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0), 0, macBytes, ref length); return new PhysicalAddress(macBytes); } private void txtIPserver_TextChanged(object sender, EventArgs e) { if ((txtIPserver.Text.Length > 0) && (txtPort.Text.Length > 0)) { btnOK.Enabled = true; } else { btnOK.Enabled = false; } } private void txtPort_TextChanged(object sender, EventArgs e) { if ((txtIPserver.Text.Length > 0) && (txtPort.Text.Length > 0)) { btnOK.Enabled = true; } else { btnOK.Enabled = false; } } } } c Class Data định nghĩa liệu trao đổi Client Server using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Server { // cau truc du lieu trao doi giua Client va Server class Data { //Default constructor public string strMac; //string MacAddress by which the client logs into Server public Command cmdCommand; //Command type (login, logout, send message, etcetera) public string strIP; //IP address public Data() { this.cmdCommand = Command.Null; this.strMac = null; this.strIP = null; } //Converts the bytes into an object of type Data public Data(byte[] data) { //The first four bytes are for the Command this.cmdCommand = (Command)BitConverter.ToInt32(data, 0); //The next four store the length of the IPadd int msgLen = BitConverter.ToInt32(data, 4); //The twelve bytes store MAC address this.strMac = Encoding.UTF8.GetString(data, 8, 12); //the nine bytes store IP address in which Server send to Old Client this.strIP = Encoding.UTF8.GetString(data, 20, msgLen); } //Converts the Data structure into an array of bytes public byte[] ToByte() { List result = new List(); //First four are for the Command result.AddRange(BitConverter.GetBytes((int)cmdCommand)); //Add the length of the IPadd result.AddRange(BitConverter.GetBytes(strIP.Length)); //Next we add the MAC add to our array of bytes result.AddRange(Encoding.UTF8.GetBytes(strMac)); // And, lastly we add IP address result.AddRange(Encoding.UTF8.GetBytes(strIP)); return result.ToArray(); } } } [...]... // Cau truc ClientInfo giu thong tin va moi Client ket noi vao server struct ClientInfo { public EndPoint endpoint; / /Socket cua Client public string strMac; //Dia chi Mac ma Client gui toi ket noi public string strIP; //dia chi IP client } // Cac Client ket noi vao Server duoc luu vao Mang ArrayList clientList,clientOld; // Socket chinh ma Server dung de lang nghe Client Socket serverSocket; // dinh... logs in to the server then we add her to our //list of clients ClientInfo clientInfo = new ClientInfo(); clientInfo.endpoint = epSender; clientInfo.strMac = msgReceived.strMac; clientInfo.strIP = msgReceived.strIP; foreach (ClientInfo client in clientOld) { if ( (client. strMac == msgReceived.strMac)&& (client. strIP == msgReceived.strIP)) { have = true; break; } //++nIndex; } clientList.Add(clientInfo);... msgToSend.cmdCommand = Command.NewClient; message = msgToSend.ToByte(); foreach (ClientInfo clientInfo in clientList) { // //if (clientInfo.endpoint != epSender) { //Gui Mac cho cac Client cu biet co client moi serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint, new AsyncCallback(OnSend), clientInfo.endpoint); } } //if (!have) toolStripStatusLabel1.Text = "Client " + msgReceived.strIP... false; // load cac client da ket noi dua vao clientOld load_old(); // Su dung UDP Socket serverSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType .Udp) ; // gan dia chi IP cua may va lang nghe Port xac dinh boi txtPort _Port = Convert.ToInt32(txtPort.Text); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, _Port); // Bind this address to Server serverSocket.Bind(ipEndPoint);... false; txtIPserver.Text = ""; txtPort.Text = "8888"; } private void btnOK_Click(object sender, EventArgs e) { //if ((textBox1.Text == "huong") && (textBox2.Text == "bkacad")) { try { // su dung UDP socket clientSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType .Udp) ; //IP address cua Server IPAddress IPserver = IPAddress.Parse(txtIPserver.Text); // lay port server lang nghe... Stop server bool _quiting; // bool _changeView; // port number cho server int _Port; //flag dung de xac dinh da startserver chua bool fstartSer; // public Form1() { InitializeComponent(); // khoi tao mang clientlist clientList = new ArrayList(); // lay dia chi card mang dang su dung //UdpClient u = new UdpClient("8.8.8.8", 1); //localAddr = ((IPEndPoint)u .Client. LocalEndPoint).Address; //txtIPserver.Text... (EndPoint)ipeSender; serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender); //} } catch (Exception ex) { MessageBox.Show(ex.Message, "ServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void OnSend(IAsyncResult ar) { try { serverSocket.EndSend(ar); } catch (Exception ex) { MessageBox.Show(ex.Message, "ServerUDP", MessageBoxButtons.OK,... break; case Command.Logout: //When a user wants to log out of the server then we search for her //in the list of clients and close the corresponding connection nIndex = 0; foreach (ClientInfo client in clientList) { if (client. strMac == msgReceived.strMac) { clientList.RemoveAt(nIndex); break; } ++nIndex; } toolStripStatusLabel1.Text = "Client " + msgReceived.strIP + " with Mac add : " + msgReceived.strMac... -1); reader.Close(); clientConnectedToolStripMenuItem.Enabled = false; clientConnectingToolStripMenuItem.Enabled = true; clientConnectingToolStripMenuItem.Checked = false; } catch (Exception eh) { MessageBox.Show(eh.Message, "SERVER _UDP" , MessageBoxButtons.OK,MessageBoxIcon.Error); clientConnectedToolStripMenuItem.Enabled = true; clientConnectingToolStripMenuItem.Enabled = false; clientConnectingToolStripMenuItem.Checked... 0);// chap nhan moi dia chi Client // xac dinh dia chi Client EndPoint epSender = (EndPoint)ipeSender; // Start receiving data serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender); // Doi text Button1 thanh Stop Server button1.Text = "Stop Server" ; toolTip1.SetToolTip(this.button1, "Click to Stop Server "); // tra gia tri ... System.Net.Sockets  Một số lớp hay dùng: TcpClient, UdpClient, TcpListener, Socket, NetworkStream, …  để tạo Socket  Socket( AddressFamily af, SocketType st, ProtocolType pt) III Lập trình Giao diện... UDP streaming media Mặc dù tổng lượng lưu thông UDP mạng thường vài phần trăm, có nhiều ứng dụng quan trọng dùng UDP, bao gồm DNS, SNMP, DHCP RIP II UDP socket a Socket Socket giao diện lập trình. .. Các loại Socket  Socket hướng kết nối (TCP Socket)  Socket không hướng kết nối (UDP Socket)  Raw Socket  ðặc điểm Socket hướng kết nối  Có đường kết nối ảo tiến trình  Một tiến trình phải

Ngày đăng: 18/11/2015, 16:04

Từ khóa liên quan

Mục lục

  • Contents

Tài liệu cùng người dùng

Tài liệu liên quan