Lập Trinh sockets,Thực hành SOCKETS

23 610 2
Lập Trinh sockets,Thực hành SOCKETS

Đ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

THỰC HÀNH TUẦN SOCKETS Lớp IP Address: lớp thể địa IP Địa tập hợp gồm số có giá trị từ đến 255 cách dấu chấm IPAddress ipadd = IPAddress.Parse(“127.0.0.1”); Lớp IPEndpoint: lớp chứa đựng IPAddress số hiệu cổng IPEndPoint RemoteIpEndPoint = new IPEndPoint(ipadd, 8080);\ Kết nối UDP Giao thức UDP giao thức phi kết nối, nói cách khác không cần thiết lập kết nối hai bên tiến hành trao đổi thông tin Giao thức không tin cậy giao thức TCP, tốc độ lại nhanh dễ cài đặt Ngoài gửi gói tin quảng bá (broadcast) đồng thời cho nhiều máy Sử dụng lớp UDPClient để thực kết nối UDP hai máy máy với nhiều máy Bài tập mẫu: (Chương 3_bài 1) Thực gởi nhận liệu hai bên sử dụng giao thức UDP Thực Hành Tuần Trang Gợi ý: Bên A – gọi UDP client, cần kết nối đến bên B – UDP server để gởi liệu Trong tập này, ta cho liệu chuỗi “Hello World?” Sự kiện cho nút Send: private void button1_Click(object sender, EventArgs e) { //Tạo kết nối UDP UdpClient udpClient = new UdpClient(); //Lấy địa IP từ textbox chuyển thành kiểu IPAddress IPAddress ipadd = IPAddress.Parse(tbHost.Text); //Thực kết nối tới UDP server địa IP address vừa gõ port 8080 udpClient.Connect(ipadd, 8080); //Do ý đồ muốn gởi liệu “Hello World?” sang bên nhận Nên cần chuyển chuỗi Hello World sang kiểu byte Byte[] sendBytes = Encoding.ASCII.GetBytes("Hello World?"); //Gởi liệu udpClient.Send(sendBytes, sendBytes.Length); } Bên B: - Sử dụng ListBox để nhận liệu từ bên A gởi - Bắt kiện xảy Form Load lên  Khai báo thành phần: private System.Windows.Forms.ListBox lbConnections; private void InitializeComponent() { this.lbConnections = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // // lbConnections // this.lbConnections.FormattingEnabled = true; this.lbConnections.ItemHeight = 16; this.lbConnections.Location = new System.Drawing.Point(14, 18); this.lbConnections.Name = "lbConnections"; this.lbConnections.Size = new System.Drawing.Size(353, 292); Thực Hành Tuần Trang this.lbConnections.TabIndex = 0; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(379, 322); this.Controls.Add(this.lbConnections); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); }  Hàm serverThread: đón nhận liệu từ bên A gởi sang lên ListBox public void serverThread() { UdpClient udpClient = new UdpClient(8080); while (true) { IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); string returnData = Encoding.ASCII.GetString(receiveBytes); string mess = RemoteIpEndPoint.Address.ToString() + ":" + returnData.ToString(); InfoMessage(mess); } } Giải thích: - Tại bên nhận, khai báo kết nối UDP với số hiệu cổng 8080 địa IPAdress Any - IPAddress.Any nghĩa socket listen từ địa ip port 8080 Sự kiện load Form: Tạo thread để chạy hàm nhận liệu từ bên gởi private void Form1_Load(object sender, EventArgs e) { Thực Hành Tuần Trang Thread thdUDPServer = new Thread(new ThreadStart(serverThread)); thdUDPServer.Start(); } Kết nối TCP Để đảm bảo độ tin cậy ứng dụng mạng, người ta sử dụng giao thức TCP _ giao thức có kết nối Bài 1: (Chương 3_ single thread) Viết chương trình lắng nghe liệu từ dịch vụ Telnet sử dụng kết nối TCP ( sử dụng lớp Socket) với mô tả sau: Chạy chương trình Nhấn nút Listen Mở CMD gõ lệnh: telnet 8080 Vào hình telnet, gõ thông điệp tùy ý, sau kết thúc, đóng cửa sổ telnet lại thông báo chương trình nhận lên form Xem hình mẫu Thực Hành Tuần Trang Gợi ý: Bật telnet win 7: http://www.wikihow.com/Activate-Telnet-in-Windows-7 Để telnet đến địa IP máy cổng 8080, ta phải mở port 8080 lắng nghe kết nối TCP đến port 8080, nhấn nút Listen có nghĩa ta thực lắng nghe kết nối địa IP máy cổng 8080 Sự kiện cho nút Listen: private void btnListen_Click(object sender, EventArgs e) { int bytesReceived = 0; // Khởi tạo mảng byte nhận liệu byte[] recv = new byte[1]; // Tạo socket bên gởi Socket clientSocket; // Tạo socket bên nhận, socket socket lắng nghe kết nối tới địa IP máy port 8080 Đây TCP/IP socket //AddressFamily: trả họ địa địa IP hành Ở địa Ipv4 nên chọn AddressFamily.InterNetwork //SocketType: kiểu kết nối socket, dùng luồng Stream để nhận liệu //ProtocolType: sử dụng giao thức kết nối nào, sử dụng kết nối TCP // Ba tham số hàm với ta thực kết nối TCP Socket listenerSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); // Dns.gethostName: lấy tên máy tính cục //Dns.GethostbyName (Dns.gethostName): trả thông tin địa IP, gồm mảng alias với địa IP kèm IPHostEntry IPHost = Dns.GetHostByName(Dns.GetHostName()); // IPHost.AddressList[0]: lấy địa IP mảng alias địa IP kèm Thực Hành Tuần Trang IPEndPoint ipepServer = new IPEndPoint(IPHost.AddressList[0], 8080); // Gán socket lắng nghe tới địa IP máy port 8080 listenerSocket.Bind(ipepServer); // bắt đầu lắng nghe Socket.Listen(int backlog) // với backlog: độ dài tối đa hàng đợi kết nối chờ xử lý listenerSocket.Listen(-1); //Đồng ý kết nối clientSocket = listenerSocket.Accept(); Nhận liệu if (clientSocket.Connected) { { bytesReceived = clientSocket.Receive(recv); tbStatus.Text += Encoding.ASCII.GetString(recv); } while (bytesReceived != 0); } } Bài ( chuong3_bai4) Viết chương trình in địa Loopback, Broadcast, None, Any kiểm tra địa IP local có phải địa IP Loopback không? Thực Hành Tuần Trang Gợi ý: static void Main(string[] args) { IPAddress test1 = IPAddress.Parse("192.168.1.1"); IPAddress test2 = IPAddress.Loopback; IPAddress test3 = IPAddress.Broadcast; IPAddress test4 = IPAddress.Any; IPAddress test5 = IPAddress.None; //IPHostEntry ihe = // Dns.GetHostByName(Dns.GetHostName()); IPHostEntry ihe = Dns.GetHostEntry(Dns.GetHostName()); IPAddress myself = ihe.AddressList[0]; if (IPAddress.IsLoopback(test2)) Console.WriteLine("The Loopback address is: {0}", test2.ToString()); else Console.WriteLine("Error obtaining the loopback address"); Console.WriteLine("The Local IP address is: {0}\n", myself.ToString()); if (myself == test2) Console.WriteLine("The loopback address is the same as local address.\n"); else Console.WriteLine("The loopback address is not the local address.\n"); Console.WriteLine("The test address is: {0}", test1.ToString()); Console.WriteLine("Broadcast address: {0}", test3.ToString()); Console.WriteLine("The ANY address is: {0}", test4.ToString()); Console.WriteLine("The NONE address is: {0}", test5.ToString()); Console.ReadLine(); } Bài 3: (Chuong _ bai 6) Viêt chương trình thực yêu cầu sau: - Khởi tạo địa IP 127.0.0.1 với cổng 8000 - Khởi tạo socket có tên test, kết nối TCP - In thuộc tính Address Family, SocketType, Protocol Type socket test - Kiểm tra xem socket có chế độ Blocking hay không? Thực Hành Tuần Trang - Set Blocking = false? Kiểm tra lại chế độ Blocking, Connected sau set blocking false - Gán địa IP + port đến socket - In địa IP + port vừa gán tới socket Gợi ý: static void Main(string[] args) { IPAddress ia = IPAddress.Parse("127.0.0.1"); IPEndPoint ie = new IPEndPoint(ia, 8000); Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Console.WriteLine("AddressFamily: {0}", test.AddressFamily); Console.WriteLine("SocketType: {0}", test.SocketType); Console.WriteLine("ProtocolType: {0}", test.ProtocolType); Console.WriteLine("Blocking: {0}", test.Blocking); test.Blocking = false; Console.WriteLine("new Blocking: {0}", test.Blocking); Console.WriteLine("Connected: {0}", test.Connected); test.Bind(ie); IPEndPoint iep = (IPEndPoint)test.LocalEndPoint; Thực Hành Tuần Trang Console.WriteLine("Local EndPoint: {0}", iep.ToString()); test.Close(); Console.ReadLine(); } Bài (Chương 3_ bai 5) Viêt chương trình thực yêu cầu sau: - Khởi tạo địa IP 127.0.0.1 với cổng 8000 - In địa IP số hiệu cổng - In thuộc tính Address Family, địa cổng - In số hiệu cổng tối thiểu tối đa - Thay đổi số hiệu cổng thành 80 - In địa IP số hiệu cổng thay đổi - In SocketAdress Gợi ý: static void Main(string[] args) Thực Hành Tuần Trang { IPAddress test1 = IPAddress.Parse("192.168.1.1"); IPEndPoint ie = new IPEndPoint(test1, 8000); Console.WriteLine("The IPEndPoint is: {0}", ie.ToString()); Console.WriteLine("The AddressFamily is: {0}", ie.AddressFamily); Console.WriteLine("The address is: {0}, and the port is: {1}\n", ie.Address, ie.Port); Console.WriteLine("The port number is: {0}", IPEndPoint.MinPort); Console.WriteLine("The max port number is: {0}\n", IPEndPoint.MaxPort); ie.Port = 80; Console.WriteLine("The changed IPEndPoint value is: {0}", ie.ToString()); SocketAddress sa = ie.Serialize(); Console.WriteLine("The SocketAddress is: {0}", sa.ToString()); Console.ReadLine(); } Bài 5: (Chương 3_bài 8) Viết chương trình lắng nghe liệu từ dịch vụ Telnet sử dụng kết nối TCP với mô tả sau: Chạy chương trình Một hình đen chữ “Waiting for a client…” Mở CMD gõ lệnh: telnet 9050 Tại hình telnet chữ “Welcome to my test sever” Tại hình chương trình chữ “Connect with địa IP at port số hiệu cổng” Vào hình telnet, gõ thông điệp tùy ý bên hình chương trình y chang Đóng hình telnet Màn hình chương trình chữ “ Disconnect at địa IP” chương trình đóng lại Xem hình mô tả Thực Hành Tuần Trang 10 Gợi ý: static void Main(string[] args) { int recv; byte[] data = new byte[1024]; 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 "); Socket client = newsock.Accept(); IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port); string welcome = "Welcome to my test server"; data = Encoding.ASCII.GetBytes(welcome); client.Send(data, data.Length, Thực Hành Tuần Trang 11 SocketFlags.None); while (true) { data = new byte[1024]; recv = client.Receive(data); if (recv == 0) break; Console.WriteLine( Encoding.ASCII.GetString(data, 0, recv)); } Console.WriteLine("Disconnected from {0}", clientep.Address); client.Close(); newsock.Close(); } Bài tập nhà Viết chương trình gửi nhận liệu sử dụng TCP Client TCP Listener Tra cưu lý thuyết:  Bật telnet win 7: http://www.wikihow.com/Activate-Telnet-in-Windows-7  system.net.sockets: https://msdn.microsoft.com/enus/library/system.net.sockets(v=vs.110).aspx  Socket: https://msdn.microsoft.com/enus/library/system.net.sockets.socket(v=vs.110).aspx  DNS: https://msdn.microsoft.com/en-us/library/system.net.dns(v=vs.110).aspx  IPHostEntry: https://msdn.microsoft.com/enus/library/system.net.iphostentry(v=vs.110).aspx Thực Hành Tuần Trang 12  IPAddress: https://msdn.microsoft.com/enus/library/system.net.ipaddress(v=vs.110).aspx  IPEndpoint : https://msdn.microsoft.com/enus/library/system.net.ipendpoint(v=vs.110).aspx Thực Hành Tuần Trang 13 Server : using using using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Net; System.Net.Sockets; System.Threading; System.IO; AxMSTSCLib; namespace Server { public partial class Form1 : Form { public Form1() { CheckForIllegalCrossThreadCalls = false; InitializeComponent(); } List listClient = new List(); Socket client; TcpListener listen; Thread t; private Stream stmReader = null; private Stream stmWriter = null; private void btn_open_Click(object sender, EventArgs e) { IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 100); listen = new TcpListener(ipe); listen.Start(); MessageBox.Show("Đang Chờ Kết Nối Từ Client"); t = new Thread(ketnoi); t.Start(); } public void ketnoi() { while (true) { client = listen.AcceptSocket(); Thực Hành Tuần Trang 14 listClient.Add(client); //MessageBox.Show("Client Kết Nối Thành Công"); //tao tuyen moi de nhan du lieu tu client co ket noi moi t = new Thread(nhandulieu); t.Start(client); string s = "Chào mừng 11520010 " + " kết nối đến máy chủ" + "\r\n"; byte[] data = new byte[1024]; data = Encoding.UTF8.GetBytes(s); client.Send(data, data.Length, SocketFlags.None); } } public void nhandulieu(object ojb) { Socket sock = (Socket)ojb; while (true) { try { // //nhan du lieu tu client byte[] data = new byte[1024]; int recv = sock.Receive(data); string s = Encoding.UTF8.GetString(data, 0, recv); rtb_hienthi.Text += s + "\r\n"; rtb_hienthi.SelectionStart = rtb_hienthi.Text.Length; rtb_hienthi.ScrollToCaret(); //tra du lieu ve cac client byte[] data1 = new byte[1024]; data1 = Encoding.UTF8.GetBytes(s); foreach (Socket i in listClient) { i.Send(data1, data1.Length, SocketFlags.None); } } catch { continue; } } } private void btn_send_Click(object sender, EventArgs e) { byte[] data = new byte[1024]; data = Encoding.UTF8.GetBytes("Server : "+txt_chat.Text); foreach (Socket i in listClient) { i.Send(data, data.Length, SocketFlags.None); } rtb_hienthi.Text +="Server : "+ txt_chat.Text + "\r\n"; rtb_hienthi.SelectionStart = rtb_hienthi.Text.Length; rtb_hienthi.ScrollToCaret(); } public byte[] filebyte(string filename) Thực Hành Tuần Trang 15 { byte[] file = File.ReadAllBytes(filename); return file; } //bool SaveData(byte[] Data) //{ // BinaryWriter Writer = null; // string Name = "book.txt"; // // // // // // // // // // // try { Writer = new BinaryWriter(File.OpenWrite(Name)); Writer.Write(Data); Writer.Flush(); Writer.Close(); } catch { return false; } // return true; //} private void btn_sendfile_Click(object sender, EventArgs e) { //byte[] data = new byte[1024]; //data = Encoding.UTF8.GetBytes("Server : Send"+txtFileName.Text); //foreach (Socket i in listClient) //{ // i.Send(data, data.Length, SocketFlags.None); //} //OpenFileDialog fileDialog = new OpenFileDialog(); //if (fileDialog.ShowDialog() == DialogResult.OK) //{ // string s = fileDialog.FileName; // string[] a = s.Split('.'); // byte[] data1 = new byte[1024]; // data = Encoding.UTF8.GetBytes(a[1]); // client.Send(data); // // client.Send(filebyte(fileDialog.FileName)); //} //} OpenFileDialog fileDialog = new OpenFileDialog(); if (fileDialog.ShowDialog() == DialogResult.OK) { string s = fileDialog.FileName; client.SendFile(s); } } private void Form1_Load(object sender, EventArgs e) { } Thực Hành Tuần Trang 16 private void button1_Click(object sender, EventArgs e) { IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 100); listen = new TcpListener(ipe); listen.Start(); //MessageBox.Show("Đang Chờ Kết Nối Từ Client"); t = new Thread(ketnoi); t.Start(); } //private void btn_brow_Click(object sender, EventArgs e) //{ // OpenFileDialog fileDialog = new OpenFileDialog(); // if (fileDialog.ShowDialog(this) == DialogResult.OK) // { // txtFileName.Text = fileDialog.FileName; // } //} //private void toolStripButton1_Click(object sender, EventArgs e) //{ // // // // // // for (int i = 0; i < lsb_1.Items.Count; i++) { string s = lsb_1.SelectedItem.ToString(); //rdp.Server = s; //rdp.Connect(); //MessageBox.Show(s); // // // // // // // // //} //} AxMsRdpClient7 rdp = new AxMsRdpClient7(); rdp.AdvancedSettings6.RDPPort = Convert.ToInt16(s); //rdp.UserName = username; //IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx(); //secured.ClearTextPassword = password; rdp.Connect(); } } } Thực Hành Tuần Trang 17 using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.IO; System.Net; System.Net.Sockets; namespace Server { public partial class SendFile : Form { public SendFile() { InitializeComponent(); } public string GetIP() { string name = Dns.GetHostName(); IPHostEntry entry = Dns.GetHostEntry(name); IPAddress[] addr = entry.AddressList; if (addr[1].ToString().Split('.').Length == 4) { return addr[1].ToString(); } return addr[2].ToString(); } public void btn_send_Click(object sender, EventArgs e) { try { StreamReader sr = new StreamReader(txtFileName.Text); TcpClient tcpClient = new TcpClient(); tcpClient.Connect(new IPEndPoint(IPAddress.Parse(GetIP()), 8085)); byte[] buffer = new byte[1500]; long bytesSent = 0; while (bytesSent < sr.BaseStream.Length) { int bytesRead = sr.BaseStream.Read(buffer, 0, 1500); tcpClient.GetStream().Write(buffer, 0, bytesRead); listBox1.Items.Add(bytesRead + " bytes sent."); bytesSent += bytesRead; } Thực Hành Tuần Trang 18 tcpClient.Close(); listBox1.Items.Add("finished"); Console.ReadLine(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void pro_1_Click(object sender, EventArgs e) { } private void btn_brow_Click(object sender, EventArgs e) { OpenFileDialog op = new OpenFileDialog(); op.ShowDialog(); txtFileName.Text = op.FileName; } private void txtFileName_TextChanged(object sender, EventArgs e) { } } } Thực Hành Tuần Trang 19 Client: using using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Threading; System.Net; System.Net.Sockets; System.IO; namespace Client { public partial class Form1 : Form { public Form1() { CheckForIllegalCrossThreadCalls = false; InitializeComponent(); } Thread truyen; Socket client; private void btn_connec_Click(object sender, EventArgs e) { IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(txt_ip.Text), 100); client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(ipe); //MessageBox.Show("Đã Kết Nối Đến Server"); byte[] data = new byte[1024]; int recv = client.Receive(data); rtb_hienthi.Text = Encoding.UTF8.GetString(data, 0, recv); truyen = new Thread(new ThreadStart(nhandulieu)); truyen.Start(); } public void nhandulieu() { while (true) { byte[] data = new byte[1024*50000]; int recv = client.Receive(data); string s = Encoding.UTF8.GetString(data, 0, recv); Thực Hành Tuần Trang 20 //string m = Encoding.UTF8.GetString(data, 0, recv); rtb_hienthi.Text += s + "\r\n"; rtb_hienthi.SelectionStart = rtb_hienthi.Text.Length; rtb_hienthi.ScrollToCaret(); } } private void btn_send_Click(object sender, EventArgs e) { //txt_name.ReadOnly = true; byte[] data = new byte[1024]; data = Encoding.UTF8.GetBytes("11520010" + " : " + txt_chat.Text); client.Send(data, data.Length, SocketFlags.None); rtb_hienthi.SelectionStart = rtb_hienthi.Text.Length; rtb_hienthi.ScrollToCaret(); } //private void btn_create_Click(object sender, EventArgs e) //{ // txt_name.Enabled = false; // txt_name.ReadOnly = true; // btn_create.Enabled = false; // //txt_name = "11520010"; //} private void button1_Click(object sender, EventArgs e) { this.Close(); } //private Stream stmReader = null; //private NetworkStream nwkStream = null; //private Stream stmWriter = null; //private TcpClient tcpClient = null; //bool SaveData(byte[] Data) //{ // BinaryWriter Writer = null; // string Name = "book.txt"; // // // // // // // // // // // try { Writer = new BinaryWriter(File.OpenWrite(Name)); Writer.Write(Data); Writer.Flush(); Writer.Close(); } catch { return false; } // return true; //} //private void btn_nhanfile_Click(object sender, EventArgs e) //{ Thực Hành Tuần Trang 21 // // // // // //lay het du lieu file byte[] data = new byte[1024 * 50000]; int recv = client.Receive(data); string s = Encoding.UTF8.GetString(data, 0, recv); // // // // // // //} byte[] data1 = new byte[1024 * 50000]; data1 = Encoding.UTF8.GetBytes(s); //int a = client.Receive(data1); File.WriteAllBytes("bb.", data1); MessageBox.Show("nhan cong"); } } Thực Hành Tuần Trang 22 using using using using System; System.Collections.Generic; System.Linq; System.Windows.Forms; namespace Client { static class Program { /// /// The main entry point for the application /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } Thực Hành Tuần Trang 23 [...]... http://www.wikihow.com/Activate-Telnet-in-Windows-7  system.net .sockets: https://msdn.microsoft.com/enus/library/system.net .sockets( v=vs.110).aspx  Socket: https://msdn.microsoft.com/enus/library/system.net .sockets. socket(v=vs.110).aspx  DNS: https://msdn.microsoft.com/en-us/library/system.net.dns(v=vs.110).aspx  IPHostEntry: https://msdn.microsoft.com/enus/library/system.net.iphostentry(v=vs.110).aspx Thực Hành Tuần 3 Trang 12  IPAddress:... https://msdn.microsoft.com/enus/library/system.net.ipendpoint(v=vs.110).aspx Thực Hành Tuần 3 Trang 13 Server : using using using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Net; System.Net .Sockets; System.Threading; System.IO; AxMSTSCLib; namespace Server... listen.Start(); MessageBox.Show("Đang Chờ Kết Nối Từ Client"); t = new Thread(ketnoi); t.Start(); } public void ketnoi() { while (true) { client = listen.AcceptSocket(); Thực Hành Tuần 3 Trang 14 listClient.Add(client); //MessageBox.Show("Client Kết Nối Thành Công"); //tao 1 tuyen moi de nhan du lieu tu client khi co ket noi moi t = new Thread(nhandulieu); t.Start(client); string s = "Chào mừng 11520010 " + " đã... (IMsTscNonScriptable)rdp.GetOcx(); //secured.ClearTextPassword = password; rdp.Connect(); } } } Thực Hành Tuần 3 Trang 17 using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.IO; System.Net; System.Net .Sockets; namespace Server { public partial class SendFile : Form { public... txtFileName_TextChanged(object sender, EventArgs e) { } } } Thực Hành Tuần 3 Trang 19 Client: using using using using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Threading; System.Net; System.Net .Sockets; System.IO; namespace Client { public partial class Form1... Thực Hành Tuần 3 Trang 21 // // // // // //lay het du lieu trong file byte[] data = new byte[1024 * 50000]; int recv = client.Receive(data); string s = Encoding.UTF8.GetString(data, 0, recv); // // // // // // //} byte[] data1 = new byte[1024 * 50000]; data1 = Encoding.UTF8.GetBytes(s); //int a = client.Receive(data1); File.WriteAllBytes("bb.", data1); MessageBox.Show("nhan thanh cong"); } } Thực Hành. .. Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port); string welcome = "Welcome to my test server"; data = Encoding.ASCII.GetBytes(welcome); client.Send(data, data.Length, Thực Hành Tuần 3 Trang 11 SocketFlags.None); while (true) { data = new byte[1024]; recv = client.Receive(data); if (recv == 0) break; Console.WriteLine( Encoding.ASCII.GetString(data, 0, recv)); } Console.WriteLine("Disconnected... sr.BaseStream.Length) { int bytesRead = sr.BaseStream.Read(buffer, 0, 1500); tcpClient.GetStream().Write(buffer, 0, bytesRead); listBox1.Items.Add(bytesRead + " bytes sent."); bytesSent += bytesRead; } Thực Hành Tuần 3 Trang 18 tcpClient.Close(); listBox1.Items.Add("finished"); Console.ReadLine(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void pro_1_Click(object sender, EventArgs e)... SocketFlags.None); } rtb_hienthi.Text +="Server : "+ txt_chat.Text + "\r\n"; rtb_hienthi.SelectionStart = rtb_hienthi.Text.Length; rtb_hienthi.ScrollToCaret(); } public byte[] filebyte(string filename) Thực Hành Tuần 3 Trang 15 { byte[] file = File.ReadAllBytes(filename); return file; } //bool SaveData(byte[] Data) //{ // BinaryWriter Writer = null; // string Name = "book.txt"; // // // // // // // // //... ThreadStart(nhandulieu)); truyen.Start(); } public void nhandulieu() { while (true) { byte[] data = new byte[1024*50000]; int recv = client.Receive(data); string s = Encoding.UTF8.GetString(data, 0, recv); Thực Hành Tuần 3 Trang 20 //string m = Encoding.UTF8.GetString(data, 0, recv); rtb_hienthi.Text += s + "\r\n"; rtb_hienthi.SelectionStart = rtb_hienthi.Text.Length; rtb_hienthi.ScrollToCaret(); } } private ... http://www.wikihow.com/Activate-Telnet-in-Windows-7  system.net .sockets: https://msdn.microsoft.com/enus/library/system.net .sockets( v=vs.110).aspx  Socket: https://msdn.microsoft.com/enus/library/system.net .sockets. socket(v=vs.110).aspx... cổng tối thiểu tối đa - Thay đổi số hiệu cổng thành 80 - In địa IP số hiệu cổng thay đổi - In SocketAdress Gợi ý: static void Main(string[] args) Thực Hành Tuần Trang { IPAddress test1 = IPAddress.Parse("192.168.1.1");... ketnoi() { while (true) { client = listen.AcceptSocket(); Thực Hành Tuần Trang 14 listClient.Add(client); //MessageBox.Show("Client Kết Nối Thành Công"); //tao tuyen moi de nhan du lieu tu client co

Ngày đăng: 30/10/2015, 15:22

Từ khóa liên quan

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

Tài liệu liên quan