Easily define your own network communication protocol

xiaoxiao2021-03-06  78

Each time you write a design network communication program, you always face a problem, that is to customize a set of application protocols (ie communication protocols), then write the corresponding method to resolve the protocol, and provide the corresponding interface to the upper layer call. If it is easy to simply text information, it is easy to exchange some control information or complex data, such as a online game, is a headache.

I recently suddenly thought of a point, and the object serialization can be used directly to convert the object directly into binary data transmission, and then directly restore it as an object. The specific process is that the data to be sent is placed in a HashTable. After serialization, the receiver receives the data and restores it to HashTable, according to the pre-approximate Key and the data that you care. In this case, the content of the definition communication protocol is essentially only specified a group of Key. Never do to do how long the types of irritability are what types of sequences are.

Many people may be very good at using XML and will be widely used in network communication. XML has an uncomfortable benefit because it is independent of the platform, and basically any development language has an existing library to parse XML. This is not conflict with my view. Object Serialization is not limited to binary data. There is a wealth of methods in C #, you can serialize the object to an XML document, and also supports serializing data with the SOAP protocol. So just serialize the object with a public serialization standard, it can also achieve a cross-platform, trans-language purpose. In fact, it is probably in the popular Web Service.

The principle is finished, and the patch code is an example. ObjectTransferClient (Abbreviation OTC) is a library that encompasses objects transmitted and received by UDP protocols and binary objects. The calling method is very simple, transmit an object with Send, respond to the ReceiveObject event to process the received object. As for the specific details, it will not be described, and it is believed that people with a C # foundation can be easily understood.

The application potential of this principle is huge, I will take the brick here, please advise. Using system; using system.net; using system.runtime.serialization.formatters.binary; using system.thream; namespace otc {///

/// Object Transfer, UDP protocol Transfer objects between different hosts through the network. /// public class ObjectTransferClient: IDisposable {private Thread ListenThread; private BinaryFormatter Serializer = new BinaryFormatter (); private int m_Port; private UdpClient m_Client; private bool m_IsStart; private bool m_IsConnected;

///

/// Receive Object Event /// Public Event ReceiveObjectEventHandler ReceiveObject;

///

///> A object transmitter, the default port 7321 /// public objectTransferClient (): this (7321) {// // Todo: Add constructor logic //// }

///

/// Specify port number to build an object transmitter. /// /// port number public objectTransferclient (int port) {this.m_port = port; this.m_isconnected = false;}} /// /// Initialize the transmitter and starts working /// public void start () {if (! this.m_isstart) {this.m_client = new udpclient (this.m_port); listenThread = New Thread (New Threadstart (this.listen)); listenRead.start (); this.m_isstart = true;}}

///

/// Use the specified host name and port connection default remote host /// /// hostname /// port public void connection, int port) {this.m_client.connect (Hostname, Port);}

///

/// Use the specified IP address and port connection default remote host ///// /// IP address /// port public void connect (ipaddress ipaddress, int port) {this.m_client.connect (ipaddress, port);}

///

/// Using network endpoints Connection Default remote host //// /// network endpoint public void connection (ipendpoint iep) { THIS.M_CLIENT.CONNECT (IEP);

private byte [] CreateArgPackage (object obj) {IPEndPoint local = new IPEndPoint (IPAddress.Any, this.m_Port); System.IO.MemoryStream outStream = new System.IO.MemoryStream (); this.Serializer.Serialize (outStream, new ReceiveObjectEventArgs (Obj, local)); return outstream.toarray ();

///

/// Sends an object to the default host. You must call the Connect method to connect to the default host before calling this method. /// /// Objects To send public void send (object obj) {if (this.isconnected) {byte [] data = this.createargpackage Obj); this.m_client.send (data, data.length);} else {throw new exception ("must first connect the default host");}}} /// /// Transmit object to the specified host . This method is not available if the Connect method is called to connect the default host. /// /// The object to send /// Target host network endpoint public void send Object obj, IpendPoint Remoteiep) {if (this.isconnected) {throw new exception ("already connected to the default host");} else {byte [] Data = this.createargpackage (obj); this.m_client.send (DATA, Data.Length, Remoteiep);}}

///

/// Listening to receiving data thread method /// protected void listen () {binaryformatter Serializer = new binaryformatter (); ipendpoint remoteipendpoint = new ipndpoint (iPaddress.any, 0); while true) {try {object revobj = Serializer.Deserialize (new System.IO.MemoryStream (m_Client.Receive (ref RemoteIpEndPoint))); ReceiveObjectEventArgs revarg = (ReceiveObjectEventArgs) revobj; RemoteIpEndPoint.Port = revarg.RemoteIEP.Port; revarg.RemoteIEP = RemoteipendPoint; if (this.ReceiveObject! = Null) {this.ReceiveObject (this, revarg);}} catch}}}}}}}}}}}}}}}

#Region Public Attribute Area

///

/// Return or set the port number ///

///

/// Returns whether the transmitter has initialized and started /// public bool isstart {get {return this.m_isstart;}} /// /// Return object Whether the sender has been connected to the default remote host /// public bool isconnected {get {return this.m_isconnected;}}

#ndregion

#Region IDisposable member

Public void dispose () {// Todo: Add ObjectTransferClient.dispose Implementim_close (); this.listenthread.abort ();} #ENDREGON} ///

/// Receive object event parameter // / [serializable] public class receiveObjectEventArgs: Eventargs {private object_obj; private system.net.ipendpoint_IEP;

///

/// Build a parameter /// /// received object /// sender's network endpoint Internal receiveObjectEventEventArgs (object obj, system.net.ipendpoint ip) {this._obj = obj; excitation ._iep = ip;}

///

/// Build an empty receiving object event parameter /// public receiveObjectEventArgs (): this (null, null) {}

///

/// Received object /// public object obj {get {return this._obj;}} /// /// transmit party network endpoint ///// public system.net.IpendPoint Remoteiep {get {returnşn_iep;} set {this._iep = value;}}} /// /// Receive object events /// Public Delegate Void ReceiveObjectEventHandler (Object Sender, ReceiveObjectEventArgs E);

转载请注明原文地址:https://www.9cbs.com/read-88886.html

New Post(0)