Modding:Network API: Difference between revisions

From Vintage Story Wiki
Line 32: Line 32:
== ProtoContracts ==
== ProtoContracts ==


VintageStory uses the [https://github.com/protobuf-net/protobuf-net Protobuf-net] library to serialize classes declared with the ProtoContract attribute. ProtoBuf is beyond the scope of this tutorial, but you can read more about this powerful library [https://developers.google.com/protocol-buffers/docs/csharptutorial here].
VintageStory uses the [https://github.com/protobuf-net/protobuf-net Protobuf-net] library to serialize classes declared with the <code>ProtoContract</code> attribute.  


Inside our namespace block, let's create our ProtoContract classes:
Inside our namespace block, let's create our <code>ProtoContract</code> classes:


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 49: Line 49:
     }
     }
</syntaxhighlight>
</syntaxhighlight>
The argument we pass to <code>ProtoContract</code> makes it so all <code>public</code> fields will be serialized; without this, we'd declare fields for serialization by using <code>ProtoMember</code> attributes. If we chose this approach, we'd write our classes like so:
<syntaxhighlight lang="c#">
[ProtoContract()]
    public class NetworkApiTestMessage
    {
        [ProtoMember(1)]
        public string message;
    }
    [ProtoContract()]
    public class NetworkApiTestResponse
    {
        [ProtoMember(1)]
        public string response;
    }
</syntaxhighlight>
The argument we pass to <code>ProtoMember</code> is a unique unsigned integer called a tag, and it's used to identify the fields flagged for serialization. When the client receives the packet containing the serialized <code>ProtoContract</code>, it won't know the type of its members, and will identify them by the tag number. We use the <code>ImplicitFields.AllPublic</code> to flag all public fields for serialization, and tags are assigned in alphabetic order. ProtoBuf is beyond the scope of this tutorial, but you can read more about this powerful library [https://developers.google.com/protocol-buffers/docs/csharptutorial here].


The fields in these classes hold the data we wish to send through our channel. We'll use <code>NetworkApiTestMessage</code> to encase the initial message from the server, while <code>NetWorkApiTestResponse</code> will be used by the Client to send its response.
The fields in these classes hold the data we wish to send through our channel. We'll use <code>NetworkApiTestMessage</code> to encase the initial message from the server, while <code>NetWorkApiTestResponse</code> will be used by the Client to send its response.