Easily define your own network communication protocols

Source: Internet
Author: User
Tags object serialization

Every time you write and design a network communication program, you always have to deal with the problem of customizing a set of application protocols (that is, communication protocols) and then writing corresponding methods to parse the protocols, and provides corresponding interfaces for upper-layer calls. It is easy to communicate text information, but it is a headache to exchange control information or complex data, such as online games.

Recently, I suddenly came up with an idea that object serialization technology can be used to directly convert an object into binary data for sending, and then directly restore it to an object upon receiving it. The specific process is that the data to be sent is put in a hashtable, serialized and sent out, and the data received by the receiver is restored to hashtable, obtain the data you are concerned about Based on the predefined key. In this case, the definition of the communication protocol is essentially just a set of keys. You no longer have to worry about the type of the specified fields.

Many may be very good at using XML and widely used for network communication. XML has incomparable advantages because it is platform-independent and basically any development language has a ready-made library to parse XML. This does not conflict with my point of view. Object serialization is not limited to binary data. C # provides a variety of methods to serialize objects into XML documents. It also supports serializing data using the SOAP protocol. Therefore, as long as public serialization standards are used to serialize objects, cross-platform and cross-language objects can also be achieved. In fact, the core technology of the popular Web Service is probably like this.

After the principles are completed, paste the Code as an example. Objecttransferclient (OTC) is a database that uses UDP protocol and binary object serialization, including object sending and receiving. The call method is simple. Send an object and respond to the receiveobject event to process the received object. As for the specific details, I believe that people with a certain C # foundation can easily understand the details.

The application potential of this principle is huge. I would like to give you some suggestions here.
Using system;
Using system. net. Sockets;
Using system. net;
Using system. runtime. serialization. formatters. Binary;
Using system. Threading;
Namespace OTC
{
/// <Summary>
/// Object transmission protocol, which uses UDP protocol to transmit objects between different hosts over the network.
/// </Summary>
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;

/// <Summary>
/// Receives the object event
/// </Summary>
Public event receiveobjecteventhandler receiveobject;

/// <Summary>
/// Construct an object upload rule. The default port is 7321.
/// </Summary>
Public objecttransferclient (): This (7321)
{
//
// Todo: add the constructor logic here
//
}

/// <Summary>
/// Specify the port number to build an object uploader.
/// </Summary>
/// <Param name = "Port"> port number </param>
Public objecttransferclient (INT port)
{
This. m_port = port;
This. m_isconnected = false;
This. m_isstart = false;
}

/// <Summary>
/// Initialize the upload task and start working
/// </Summary>
Public void start ()
{
If (! This. m_isstart)
{
This. m_client = new udpclient (this. m_port );
Listenthread = new thread (New threadstart (this. Listen ));
Listenthread. Start ();
This. m_isstart = true;
}
}

/// <Summary>
/// Use the specified host name and port to connect to the default remote host
/// </Summary>
/// <Param name = "hostname"> host name </param>
/// <Param name = "Port"> port </param>
Public void connect (string hostname, int port)
{
This. m_client.connect (hostname, Port );
}

/// <Summary>
/// Use the specified IP address and port to connect to the default remote host
/// </Summary>
/// <Param name = "IPaddress"> ip address </param>
/// <Param name = "Port"> port </param>
Public void connect (IPaddress, int port)
{
This. m_client.connect (IPaddress, Port );
}

/// <Summary>
/// Use the network endpoint to connect to the default remote host
/// </Summary>
/// <Param name = "IEP"> network endpoint </param>
Public void connect (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 ();
}

/// <Summary>
/// Send the object to the default host. Before calling this method, you must call the connect method to connect to the default host.
/// </Summary>
/// <Param name = "OBJ"> object to be sent </param>
Public void send (Object OBJ)
{
If (this. isconnected)
{
Byte [] DATA = This. createargpackage (OBJ );
This. m_client.send (data, data. Length );
}
Else
{
Throw new exception ("You must connect to the default host first ");
}
}

/// <Summary>
/// Send the object to the specified host. If the connect method is called to connect to the default host, this method is unavailable.
/// </Summary>
/// <Param name = "OBJ"> object to be sent </param>
/// <Param name = "remoteiep"> network endpoint of the target host </param>
Public void send (Object OBJ, ipendpoint remoteiep)
{
If (this. isconnected)
{
Throw new exception ("the default host has been connected ");
}
Else
{
Byte [] DATA = This. createargpackage (OBJ );
This. m_client.send (data, data. length, remoteiep );
}
}

/// <Summary>
/// Method for listening to the thread that receives data
/// </Summary>
Protected void listen ()
{
Binaryformatter serializer = new binaryformatter ();
Ipendpoint remoteipendpoint = new ipendpoint (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
{
Break;
}
}
}

# Region Public attribute Zone

/// <Summary>
/// Return or set the port number of the recipient
/// </Summary>
Public int Port
{
Get
{
Return this. m_port;
}
Set
{
This. m_port = value;
}
}

/// <Summary>
/// Return whether the object sender has been initialized and started to work
/// </Summary>
Public bool isstart
{
Get
{
Return this. m_isstart;
}
}

/// <Summary>
/// Return whether the object sender is connected to the default remote host
/// </Summary>
Public bool isconnected
{
Get
{
Return this. m_isconnected;
}
}

# Endregion

# Region idisposable Member

Public void dispose ()
{
// Todo: Add objecttransferclient. Dispose implementation
This. m_client.close ();
This. listenthread. Abort ();
}
# Endregion
}

/// <Summary>
/// Parameters of the received object event
/// </Summary>
[Serializable]
Public class receiveobjecteventargs: eventargs
{
Private object _ OBJ;
Private system. net. ipendpoint _ IEP;

/// <Summary>
/// Construct a parameter for receiving object events
/// </Summary>
/// <Param name = "OBJ"> received object </param>
/// <Param name = "IEP"> network endpoint of the sender </param>
Internal receiveobjecteventargs (Object OBJ, system. net. ipendpoint IEP)
{
This. _ OBJ = OBJ;
This. _ IEP = IEP;
}

/// <Summary>
/// Construct an empty receiving object event Parameter
/// </Summary>
Public receiveobjecteventargs (): This (null, null)
{
}

/// <Summary>
/// Received object
/// </Summary>
Public object OBJ
{
Get
{
Return this. _ OBJ;
}
}
/// <Summary>
/// The network endpoint of the sender
/// </Summary>
Public System. net. ipendpoint remoteiep
{
Get
{
Return this. _ IEP;
}
Set
{
This. _ IEP = value;
}
}
}

/// <Summary>
/// Receive the delegate of the object event
/// </Summary>
Public Delegate void receiveobjecteventhandler (Object sender, receiveobjecteventargs E );
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.