반응형
C# 으로 하는 Protobuf
https://github.com/protocolbuffers/protobuf/releases
Releases · protocolbuffers/protobuf
Protocol Buffers - Google's data interchange format - protocolbuffers/protobuf
github.com
여기서 protoc-{"버전"}-win64.zip을 다운로드!
압축을 풀면 위의 파일이 생성됨
protoc-21.2-win64/bin 폴더에 보면 protoc.exe파일이 있는걸 볼 수 있음
bin 폴더에 배치파일, Protocol.proto 라는 이름의 파일을 만들어주고 비주얼스튜디오로 드래그앤 드롭
Protocol.proto
syntax = "proto3";
package tutorial;
import "google/protobuf/timestamp.proto";
option csharp_namespace = "Google.Protobuf.Protocol";
message Person {
string name = 1;
int32 id = 2; // Unique ID number for this person.
string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
string number = 1;
PhoneType type = 2;
}
repeated PhoneNumber phones = 4;
google.protobuf.Timestamp last_updated = 5;
}
// Our address book file is just one of these.
message AddressBook {
repeated Person people = 1;
}
배치파일
REM protoc -I=$SRC_DIR --csharp_out=$DST_DIR $SRC_DIR/addressbook.proto
REM $SRC_DIR 은 protoc의 위치, DST_DIR은 저장할 위치
REM ./ 은 현재 폴더를 의미함
protoc -I=./ --csharp_out=./ ./Protocol.proto
이후 배치파일을 실행시키면 Protocol.cs가 만들어짐
비쥬얼 스튜디오 들어가서 솔루션 우클릭 -> NuGet 누르고 Protobuf 검색후 Google.Protobuf 선택
Google의 Protobuf를 설치할 프로젝트 선택 후 설치!
그럼 이렇게 프로젝트 내에서 이런식으로 Protobuf를 쓸 수 있음
using System;
using Google.Protobuf.Protocol;
using Google.Protobuf;
namespace Server
{
class ClientSession : PacketSession
{
public int SessionId { get; set; }
public override void OnConnected(EndPoint endPoint)
{
Console.WriteLine($"OnConnected : {endPoint}");
Person person = new Person()
{
Name = "Woody",
Id = 605,
Email = "Woody0605@gmail.com",
Phones =
{
new Person.Types.PhoneNumber
{
Number = "555-4321", Type = Person.Types.PhoneType.Home
}
}
};
ushort size = (ushort)person.CalculateSize();
byte[] sendBuffer = new byte[size + 4];
// [길이정보] [아이디정보] [내용물] [ ] [ ] [ ]
Array.Copy(BitConverter.GetBytes(size + 4), 0, sendBuffer, 0, sizeof(ushort));
ushort protocolId = 1;
Array.Copy(BitConverter.GetBytes(protocolId), 0, sendBuffer, 2, sizeof(ushort));
Array.Copy(person.ToByteArray(), 0, sendBuffer, 4, size);
Send(new ArraySegment<byte>(sendBuffer));
}
Protocol.proto파일 안에 설계해둔 놈을 기반으로 통신규격을 만들어 buffer를 보내고 받는거임
반응형
LIST
'네트워크' 카테고리의 다른 글
[C#] TaskTimer (0) | 2022.06.21 |
---|---|
[C#] 패킷 효율적으로 보내기 (0) | 2022.06.21 |
[C#] JobQueue (0) | 2022.06.20 |