[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: 作成を入力してください 1 サーバーと 1 クライアント. クライアントは、情報のgethostnameを送る, gethosttime, サーバにgethostdate, サーバが受信して、名前の、対応する値を返します, 1時間, 日.

私たちは、作成 2 個々のプロジェクトmyserverという名前とMyClientという. あなたはCtrlキー私を実行すると + F5 (デバッグモードを削除し、新しいプロジェクトは、多くが経営する). 私のコードでは、比較的ので、あなたが追跡しようと指摘しています.

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 サーバーへのファイル名, 存在しないファイルサーバをチェック, 場合には、クライアントdownlodを可能に存在, そうでなければ存在していないクライアント·ファイルに通知. (ファイル名だけあれば、サーバはディレクトリの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);
            }
        }
    }
}