You are on page 1of 42

i Hc Bch Khoa H Ni Vin in t vin thng ---------------o0o---------------

BO CO BI TP LN
K thut mng nng cao ti : Lp trnh UDP socket giao tip Client Server
Ging vin hng dn: Sinh vin thc hin : Nguyn Th Hng Phm Thu Hng Nguyn Ngc Kiu

T8 - K52

20071475

H Ni, thng 10 nm 2011

Mc lc

Contents
Contents..................................................................................................................... 2

Yu cu ti: To chng trnh Client-Server trao i thng tin qua UDP socket thc hin cc chc nng sau : - Client sau khi kt ni s gi ti server thng tin v a ch Mac ca client - Server sau khi nhn thng tin s kim tra thng tin v client c ghi vo file hay cha, nu cha s lu vo file. Sau gi li client bn tin xc nhn nhn, ghi, c thng tin. - Server lu gi thng tin cc client hin ang kt ni vo server.Client mun ngt kt ni cn gi bn tin thng bo cho server - Khi c client khc kt ni vo server, server gi cho cc client khc thng tin v client mi kt ni vo.Client nhn c bn tin ny s hin th thng tin mac ca client mi kt ni vo server

I. Cc kin thc c bn v my tnh 1. H giao thc TCP/IP

Hnh 1-3: Cc tng ca giao thc TCP/IP so vi cc tng ca m hnh OSI Application: Xc nhn quyn, nn d liu v cc dch v cho ngi dng Transport: X l d liu gia cc h thng va cung cp vic truy cp mng cho cc ng dng Network: Tm ng cho cc packet Link: Mc OS hoc cc thit b giao tip mng trn mt my tnh

Mt s im khc nhau ca TCP/IP v m hnh OSI + Lp ng dng trong TCP/IP x l chc nng ca lp 5,6,7 trong m hnh OSI + Lp transport trong TCP/IP cung cp c ch UDP truyn khng tin cy, transport trong OSI lun m bo truyn tin cy + TCP/IP l mt tp ca cc protocols (mt b giao thc) + TCP/IP xy dng trc OSI 2. Giao thc UDP a. Khi qut UDP (User Datagram Protocol) l mt trong nhng giao thc ct li ca giao thc TCP/IP. Dng UDP, chng trnh trn mng my tnh c th gi nhng d liu ngn c gi l datagram ti my khc. UDP khng cung cp s tin cy v th t truyn nhn m TCP lm; cc gi d liu c th n khng ng th t hoc b mt m khng c thng bo. Tuy nhin UDP nhanh v hiu qu hn i vi cc mc tiu nh kch thc nh v yu cu kht khe v thi gian. Do bn cht khng trng thi ca n nn n hu dng i vi vic tr li cc truy vn nh vi s lng ln ngi yu cu. Nhng ng dng ph bin s dng UDP nh DNS (Domain Name System), ng dng streaming media, Voice over IP, Trivial File Transfer Protocol (TFTP), v game trc tuyn b. Cng UDP dng cng cho php cc giao tip gia cc ng dng din ra. Cng dng 16 bit nh a ch, v vy s ca cng nm trong khon 0 n 65.535. Cng 0 c dnh v khng nn s dng. Cng t 1 n 1023 c gi l cng "well-known" v trn cc h iu hnh ta Unix, vic gn kt ti mt trong nhng cng ny i hi quyn root.

Cng 1024 n 49.151 l cng ng k. Cng t 49.152 n 65.535 l cc cng tm, c dng ch yu bi client khi lin lc vi server c. Cu trc gi UDP l giao thc hng thng ip nh nht ca tng giao vn hin c m t trong RFC 768 ca IETF. Trong b giao thc TCP/IP, UDP cung cp mt giao din rt n gin gia tng mng bn di (th d, IPv4) v tng phin lm vic hoc tng ng dng pha trn. UDP khng m bo cho cc tng pha trn thng ip c gi i v ngi gi cng khng c trng thi thng ip UDP mt khi c gi (V l do ny i khi UDP cn c gi l Unreliable Datagram Protocol).

UDP ch thm cc thng tin multiplexing v giao dch. Cc loi thng tin tin cy cho vic truyn d liu nu cn phi c xy dng cc tng cao hn. Phn header ca UDP ch cha 4 trng d liu, trong c 2 trng l ty chn ( nn trong bng).
Source port Trng ny xc nh cng ca ngi gi thng tin v c ngha nu mun nhn thng tin phn hi t ngi nhn. Nu khng dng n th t n bng 0. Destination port Trng xc nh cng nhn thng tin, v trng ny l cn thit. Length Trng c di 16 bit xc nh chiu di ca ton b datagram: phn header v d liu. Chiu di ti thiu l 8 byte khi gi tin khng c d liu, ch c header. 2 Trng checksum 16 bit dng cho vic kim tra li ca phn header v d liu. Phng php tnh checksum c nh ngha trong RFC 768.

Do thiu tnh tin cy, cc ng dng UDP ni chung phi chp nhn mt mt, li hoc trng d liu. Mt s ng dng nh TFTP c nhu cu phi thm nhng k thut lm tin cy c bn vo tng ng dng. Hu ht cc ng dng UDP khng cn nhng k thut lm tin cy ny v i khi n b b i. Streaming media, game trc tuyn v voice over IP (VoIP) l nhng th d cho cc ng

dng thng dng UDP. Nu mt ng dng i hi mc cao hn v tnh tin cy, nhng giao thc nh TCP hoc m erasure c th dng thay. Thiu nhng c ch kim sot tc nghn v kim sot lung, cc k thut da trn mng l cn thit gim nguy hiu ng c tc nghn dy chuyn do khng kim sot, t l ti UDP cao. Ni cch khc, v ngi gi gi UDP khng th pht hin tc nghn, cc thnh phn da trn mng nh router dng hng i gi (packet queueing) hoc k thut b gi nh l nhng cng c gim ti ca UDP. Giao thc Datagram Congestion Control Protocol (DCCP) c thit k nh mt gii php cho vn bng cch thm hnh vi kim sot tc nghn cho thit b u cui cho cc dng d liu UDP nh streaming media. Mc d tng lng lu thng ca UDP trn mng thng ch vi phn trm, nhng c nhiu ng dng quan trng dng UDP, bao gm DNS, SNMP, DHCP v RIP. II. UDP socket a. Socket Socket l mt giao din lp trnh ng dng (API) mng Thng qua giao din ny chng ta c th lp trnh iu khin vic truyn thng gia hai my s dng cc giao thc mc thp l TCP, UDP Socket l s tru tng ho mc cao, c th tng tng n nh l thit b truyn thng hai chiu gi - nhn d liu gia hai my tnh vi nhau. Cc loi Socket Socket hng kt ni (TCP Socket) Socket khng hng kt ni (UDP Socket) Raw Socket

c im ca Socket hng kt ni C 1 ng kt ni o gia 2 tin trnh Mt trong 2 tin trnh phi i tin trnh kia yu cu kt ni. C th s dng lin lc theo m hnh Client/Server Trong m hnh Client/Server th Server lng nghe v chp nhn mt yu cu kt ni Mi thng ip gi u c xc nhn tr v Cc gi tin chuyn i tun t c im ca Socket khng hng kt ni Hai tin trnh lin lc vi nhau khng kt ni trc tip Thng ip gi i phi km theo a ch ca ngi nhn Thng ip c th gi nhiu ln Ngi gi khng chc chn thng ip ti tay ngi nhn Thng ip gi sau c th n ch trc thng ip gi trc . S hiu cng ca Socket

c th thc hin cc cuc giao tip, mt trong hai qu trnh phi cng b s hiu cng ca socket m mnh s dng. Mi cng giao tip th hin mt a ch xc nh trong h thng. Khi qu trnh c gn mt s hiu cng, n c th nhn d liu gi n cng ny t cc qu trnh khc. Qu trnh cn li cng yu cu to ra mt socket
b. Gii thiu v NameSpace System.Net v System.Net.Sockets

Cung cp mt giao din lp trnh n gin cho rt nhiu cc giao thc mng. C rt nhiu lp lp trnh Ta quan tm lp IPAdress, IPEndPoint, DNS, Lp IPAdress Mt s Field cn ch : Any: Cung cp mt a ch IP ch ra rng Server phi lng nghe trn tt c cc Card mng Broadcast: Cung cp mt a ch IP qung b Loopback: Tr v mt a ch IP lp AdressFamily: Tr v h a ch ca IP hin hnh Lp IPAddress Mt s phng thc cn ch : Phng thc khi to IPAddress(Byte[]) IPAddress(Int64) IsLoopback: Cho bit a ch c phi a ch lp khng Parse: Chuyn IP dng xu v IP chun ToString: Tr a ch IP v dng xu TryParse: Kim tra IP dng xu c hp l khng? Lp IPEndPoint Cng, v d: 192.168.1.1:8080 Lp DNS Mt s thnh phn ca lp: HostName: Cho bit tn ca my c phn gii GetHostAddress: Tr v tt c IP ca mt

trm GetHostEntry: Gii p tn hoc a ch truyn vo v tr v i tng IPHostEntry GetHostName: Ly v tn ca my tnh cc b NameSpace System.Net.Sockets Mt s lp hay dng: TcpClient, UdpClient, TcpListener, Socket, NetworkStream, to ra Socket Socket(AddressFamily af, SocketType st, ProtocolType pt) III. Lp trnh 1. Giao din a. Server Cha c client kt ni

C Client kt ni

b. Client Login

Form chnh

2. Chng trnh 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, Logout, //Dang nhap toi Server //Dang xuat khoi Server

ACK, //Thong bao da nhan, ghi, da co thong tin MAC ve Client NewClient, Null, Stop } public partial class Form1 : Form //Gui cho Client thong bao dia chi MAC Client moi ket noi

//No command //Server will stop after 5s

{ // // Cau truc ClientInfo giu thong tin va moi Client ket noi vao server struct ClientInfo { public EndPoint endpoint; //Socket cua Client public string strMac; public string strIP; } //Dia chi Mac ma Client gui toi ket noi //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 nghia mot byteData byte[] byteData = new byte[1024];

// flag quiting dung cho viec 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 = localAddr.ToString();

// Get host name String strHostName = Dns.GetHostName();

// Find host by name IPHostEntry iphostentry = Dns.GetHostByName(strHostName); // Dns.GetHostByName(strHostName);

// Enumerate IP addresses foreach (IPAddress ipaddress in iphostentry.AddressList) { comboBox1.Items.Add(ipaddress.ToString()); }

// Mac dinh Cong lang nghe la 8888 txtPort.Text = "8888"; _Port = 8888;

// Mac dinh chua chay Server fstartSer = false; button1.Text = "Start Server"; stopToolStripMenuItem.Enabled = false; toolTip1.SetToolTip(this.button1, "Click to Start Server...");

// tooltip toolTip1.SetToolTip(comboBox1, "IP address Server"); toolTip1.SetToolTip(txtPort, "Port number in which Server is listening");

// _changeView = false;

private void button1_Click(object sender, EventArgs e) { // if (fstartSer == false) { try { CheckForIllegalCrossThreadCalls = 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);

IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 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 flag StartSer ve True fstartSer = true;

// enabel nut Stop trong 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 thanh 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 thanh 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 khi 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 trong 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) { //Thot khi form th hin chui xc nhn vi biu tng cnh bo if (MessageBox.Show("Bn c chc chn thot khi chng trnh ?", "Thng Bo", 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. do { 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(); do { 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\nNguyn Th Hng\nPhm Thu Hng\nNguyn Ngc Kiu","K thut mng nng 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.

do { 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 ngha d liu trao i Client v 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<byte> result = new List<byte>();

//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(); } } }

You might also like