[Cの#] C#の経由ソケットコミュニケーションズオブジェクト

Hôm trước mình đã hướng dẫn các bạn làm ví dụ đơn giản truyền nhận quan socket trong c#, hôm nay tiếp tục hướng dẫn các bạn truyền đối tượng qua socket 😉

Bài này hướng dẫn các bạn viết chuơng trình truyền nhận đối tượng giữa client và server. Client là 1 From thông tin của 1 cuốn sách (Book) gồm tiêu đề, tác giả, năm xuất bản và thể loại. Client có 2 nút là gửi (sẽ gửi thông tin đến server) および受信 (サーバから情報を受信します). クライアントが送信すると、サーバーのボタンは、情報を受信し、サーバー上のファイルに書き込みます。. サーバが受信すると、クライアントのボタンは、ファイルを読み込み、クライアントに送信されます, クライアントがアップから受信した情報を表示します. 下の画像のように.

socket trong c#

今、私たちが構築するものの 2 プロジェクトは次のようにBookClientとBookServerを構成されています:

前日と同様のことC#でソケット通信を介したオブジェクト, 私たちは、バイト配列のオブジェクトを繰り越すと、受信を送信する必要がある唯一のもの. オブジェクトを受信することをバイト配列から機能オブジェクトを復元するために必要とされます.

ハム移動 1 バイト配列およびその逆のオブジェクト.

// nen data thanh 1 mang byte
public byte[] SerializeData(Object o)
{
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf1 = new BinaryFormatter();
    bf1.Serialize(ms, o);
    return ms.ToArray();
}

// giai nen 1 mang byte thanh 1 doi tuong (bject)
public object DeserializeData(byte[] theByteArray)
{
    MemoryStream ms = new MemoryStream(theByteArray);
    BinaryFormatter bf1 = new BinaryFormatter();
    ms.Position = 0;
    return bf1.Deserialize(ms);
}

しかし、シリアル化のキーワードを持っている必要がありオブジェクトクラスをオブジェクトの圧縮を達成することを注意してください [シリアライズ] 授業の前に. 具体的に以下のクラス帳の (クライアントのプロジェクトにBookクラス)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BookClient
{
    [Serializable]
    class Book
    {
        public String title, author, yearOfPublication, genre;
    }
}

次からのクライアントのコードです (オフラインインターフェイスのデザイン)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;

namespace BookClient
{
    public partial class Form1 : Form
    {
        Socket client;
        private const int BUFFER_SIZE = 1024;
        private const int PORT_NUMBER = 7826;
        static ASCIIEncoding encoding = new ASCIIEncoding();
        public Form1()
        {
            InitializeComponent();
            connectServer();
        }


        // ket noi den server
        private void connectServer()
        {
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), PORT_NUMBER);
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect(iep);
        }


// nen data thanh 1 mang byte
public byte[] SerializeData(Object o)
{
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf1 = new BinaryFormatter();
    bf1.Serialize(ms, o);
    return ms.ToArray();
}

// giai nen 1 mang byte thanh 1 doi tuong (bject)
public object DeserializeData(byte[] theByteArray)
{
    MemoryStream ms = new MemoryStream(theByteArray);
    BinaryFormatter bf1 = new BinaryFormatter();
    ms.Position = 0;
    return bf1.Deserialize(ms);
}

        // gui du lieu cho server
        private void btnSend_Click(object sender, EventArgs e)
        {
            // tao va lay du lieu tu form
            Book b = new Book();
            b.title = tbTitle.Text;
            b.author = tbAuthor.Text;
            b.yearOfPublication = tbYear.Text;
            b.genre = tbGenre.Text;

            // gui lenh yeu cau la client muon gui du lieu
            client.Send(encoding.GetBytes("send"));

            // gui du lieu
            client.Send(SerializeData(b));
        }

        private void btnReceive_Click(object sender, EventArgs e)
        {
            // gui lenh yeu cau lay du lieu tu server
            client.Send(encoding.GetBytes("receive"));
            byte[] data = new byte[BUFFER_SIZE];

            // nhan du lieu tu server gui xuong
            int rec = client.Receive(data);

            // hien thi thong tin nhan duoc len form
            Book b = (Book)DeserializeData(data);
            tbTitle.Text = b.title;
            tbAuthor.Text = b.author;
            tbYear.Text = b.yearOfPublication;
            tbGenre.Text = b.genre;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

コー​​ドCUAサーバ

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
namespace BookServer
{
    class Program
    {
        private const int BUFFER_SIZE = 1024;
        private const int PORT_NUMBER = 7826;

        static ASCIIEncoding encoding = new ASCIIEncoding();
        Socket server;

        // ghi data xuong file
        protected bool SaveData(byte[] Data)
        {
            BinaryWriter Writer = null;
            string Name = "book";

            try
            {
                Writer = new BinaryWriter(File.OpenWrite(Name));          
                Writer.Write(Data);
                Writer.Flush();
                Writer.Close();
            }
            catch
            {
                return false;
            }

            return true;
        }

        private void initServer()
        {
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), PORT_NUMBER);
            // tao server
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Console.WriteLine("dang cho client ket noi...");
            
            // lang nghe ket noi
            server.Bind(iep);
            server.Listen(10);

            // chap nhan client ket noi
            Socket client = server.Accept();
            Console.WriteLine("Chap nhan ket noi tu: " + client.RemoteEndPoint.ToString());
            byte[] data = new byte[BUFFER_SIZE];

            // vong lap vo han thuc hien viec nhan va gui du lieu
            while (true)
            {
                // nhan lenh: gui hoac nhan du lieu
                int rec = client.Receive(data);
                String command = encoding.GetString(data, 0, rec);
                Console.WriteLine("command = " + command);
                
                // client send data den server
                if (command.Equals("send"))
                {
                    client.Receive(data);
                    Console.WriteLine("Nhan thanh cong");
                    if (SaveData(data))
                    {
                        Console.WriteLine("Ghi thanh cong");
                    }
                    else
                    {
                        Console.WriteLine("Ghi that bai");
                    }
                }
                // client muon lay data tu server
                else
                {
                    Console.WriteLine("Dang gui...");
                    // doc du lieu tu file
                    byte[] arraydata = File.ReadAllBytes("book");
                    // gui du lieu doc duoc cho client
                    client.Send(arraydata);
                }
            }
        }

        static void Main(string[] args)
        {
            new Program().initServer();

        }
    }
}

あなたはダウンロードすることができます 2 このプロジェクトのクライアントとサーバー.