[C #] For example, the socket on C #
Dạo này đang học C# trên trường nên tiện thể viết mấy bài ghi nhớ 😉
Program 1: Enter creation 1 server and 1 customer. Client sends the information gethostname, gethosttime, gethostdate to server, server receives and returns the corresponding value of the name, hour, day.
We create 2 individual project named MyServer and MyClient. When you run the Ctrl Me + F5 (remove debug mode, the new project run by many). In my code has relatively notes so you try to track.
using System; using System.Text; using System.Net; using System.Net.Sockets; namespace MyServer { class Program { private const int BUFFER_SIZE = 1024; private const int PORT_NUMBER = 7826; static ASCIIEncoding encoding = new ASCIIEncoding(); public static void Main() { try { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), PORT_NUMBER); Console.WriteLine("dang cho client ket noi..."); // tao ra server Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); // server lang nghe ket noi tu client server.Bind(iep); server.Listen(10); Socket client = server.Accept(); Console.WriteLine("Chap nhan ket noi tu: " + client.RemoteEndPoint.ToString()); byte[] data = new byte[BUFFER_SIZE]; String result = ""; while (true) { // nhan du lieu tu client int rec = client.Receive(data); // chuyen ve string string command = encoding.GetString(data, 0, rec); Console.WriteLine("Client: " + command); if (command.Equals("gethostname")) { // lay ten server IPEndPoint endPoint = (IPEndPoint)client.RemoteEndPoint; IPAddress ipAddress = endPoint.Address; IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress); result = hostEntry.HostName; } else if (command.Equals("gethosttime")) { // lay thoi gian result = DateTime.Now.ToString("h:mm:ss tt"); } else if (command.Equals("gethostdate")) { // lay ngay result= DateTime.Now.ToString("dd:MM:yyyy"); } else if (command.Equals("quit")) { // dong server.Close(); client.Close(); break; } else { result = "khong phai lenh dung"; } // tra ve ket qua cho client client.Send(encoding.GetBytes(result)); } } catch (Exception ex) { Console.WriteLine("Error: " + ex); } } } }
using System; using System.IO; using System.Net; using System.Text; using System.Net.Sockets; namespace MyClient { class Program { private const int BUFFER_SIZE = 1024; private const int PORT_NUMBER = 7826; static ASCIIEncoding encoding = new ASCIIEncoding(); public static void Main() { try { // IPAddress address = IPAddress.Parse("127.0.0.1"); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), PORT_NUMBER); // tao ra client Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // client connect den cong client.Connect(iep); String command = ""; while (!command.Equals("quit")) { // cho nhap lenh command = Console.ReadLine(); // gui lenh client.Send(encoding.GetBytes(command)); byte[] data = new byte[BUFFER_SIZE]; int rec = client.Receive(data); Console.WriteLine("server: " + encoding.GetString(data, 0, rec)); } client.Close(); } catch (Exception ex) { Console.WriteLine("Error: " + ex); } } } }
Program 2: Client sends 1 file name to server, check file server that does not exist, if exists, allowing client downlod, otherwise notified to the client file does not exist. (Note that if only the file name, the server will look in the directory bin / Debug /)
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; namespace MyServer { class Program { private const int BUFFER_SIZE = 1024; private const int PORT_NUMBER = 7826; static ASCIIEncoding encoding = new ASCIIEncoding(); public static void Main() { try { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), PORT_NUMBER); Console.WriteLine("dang cho client ket noi..."); // tao ra server Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // server lang nghe ket noi tu client server.Bind(iep); server.Listen(10); Socket client = server.Accept(); Console.WriteLine("Chap nhan ket noi tu: " + client.RemoteEndPoint.ToString()); byte[] data = new byte[BUFFER_SIZE]; // lap vo han while (true) { // nhan du lieu tu client int rec = client.Receive(data); // chuyen ve string string fileName = encoding.GetString(data, 0, rec); Console.WriteLine("Client: " + fileName); // neu file ton tai if (File.Exists(fileName)) { // gui thong bao la co tim thay file client.Send(encoding.GetBytes("yes")); // gui file xuong client byte[] fileData = File.ReadAllBytes(fileName); byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName); byte[] servertData = new byte[4 + fileNameByte.Length + fileData.Length]; byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length]; byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length); fileNameLen.CopyTo(servertData, 0); fileNameByte.CopyTo(servertData, 4); fileData.CopyTo(servertData, 4 + fileNameByte.Length); client.Send(servertData); Console.WriteLine("Da gui file " + fileName + " den client!"); client.Close(); // thoat break; } // khong tim thay file else { // gui thong bao khong tim thay file client.Send(encoding.GetBytes("no")); Console.WriteLine("khong thay file"); } } } catch (Exception ex) { Console.WriteLine("Error: " + ex); } } } }
using System; using System.IO; using System.Net; using System.Text; using System.Net.Sockets; namespace MyClientSendFile { class Program { private const int BUFFER_SIZE = 1024; private const int PORT_NUMBER = 7826; static ASCIIEncoding encoding = new ASCIIEncoding(); public static void Main() { try { // IPAddress address = IPAddress.Parse("127.0.0.1"); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), PORT_NUMBER); // tao ra client Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // client connect den cong client.Connect(iep); // lap vo han while (true) { // nhap file can tai xuong Console.Write("Nhap file muon download: "); String fileName = Console.ReadLine(); // gui ten file len server client.Send(encoding.GetBytes(fileName)); // nhan thong bao co tim thay hay khong byte[] data = new byte[BUFFER_SIZE]; int rec = client.Receive(data); String check = encoding.GetString(data, 0, rec); // neu tim thay thi thuc hien viec nhan file if (check.Equals("yes")) { byte[] serverData = new byte[1024 * 5000]; int receivedBytesLen = client.Receive(serverData); int fileNameLen = BitConverter.ToInt32(serverData, 0); BinaryWriter bWrite = new BinaryWriter(File.Open(fileName, FileMode.Append)); bWrite.Write(serverData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen); Console.WriteLine("Da nhan file " + fileName + " tu server!"); bWrite.Close(); // thoat break; } // neu khong tim thay thi bat nhap lai else { Console.WriteLine("Server khong co file " + fileName); } } client.Close(); } catch (Exception ex) { Console.WriteLine("Error: " + ex); } } } }
Welcome, bạn có thể cho mình hỏi tài liệu học tiếng việt về lập trình mạng, hoặc nguồn học trên mạng ở đâu?
Thanks a lot!
Cái này mình chỉ google thôi, và toàn google tiếng anh hết bạn ah
anh cho em hỏi chỗ ipe của client là khi truyền IPAddress vào là IP của client hay server vậy?
Của server bạn nhé, đang cần kết nối đến server mà.
Ask yourself, eg electronic cash trading platform for users to write their binance.com tool to trade, provide real-time data, ordered sale by API. Ask yourself can use C # to write tool, soft or not, and need to use the soft or any other auxiliary tool. Thank you!
This alone is not clear ah.