[C#] 例如,在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ớ 😉

计划 1: Nhập tạo 1 server và 1 client. Client gửi các thông tin gethostname, gethosttime, gethostdate đến server, server nhận và trả về tương ứng các giá trị tên, giờ, 天.

Chúng ta tạo 2 名为MyServer和MyClient的单独项目. 运行时,请记住按Ctrl + F5 (bỏ chế độ debug thì mới chạy được nhiều project). 在他的代码是相对的笔记,你应该设法跟踪.

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

计划 2: 客户端发送 1 文件名的服务器上, 服务器会检查文件是否存在, 如果客户端存在,让Gamespot的, 否则该通知不存在客户端文件. (请注意,如果只有文件名,服务器将看在目录的bin /调试/)

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