Use SuperSocket to implement TLV custom protocol network communication Demo

Source: Internet
Author: User

A few days ago, I saw the official version of SuperSocket 1.4 released by Jiang Dayu. Due to the use of network port communication programming in recent projects, I also checked the SuperSocket source code and found that the architecture is still clear and easy to expand, for detailed Chinese documents, see http://www.cnblogs.com/jzywh/archive/2011/04/19/supersocketdocument.html.

 

Today, I want to talk about customizing an application protocol through SuperSocket. The services in the project transmit data through the TLV protocol, while the network port is one of the communication methods. Of course, the project also includes data transmission through serial ports, USB devices, and USB data lines. The network port communication adopts TCP communication. What is TLV? refer to an article I wrote earlier: "Implementation of TLV algorithms for PBOC/EMV in financial systems", which gives a detailed introduction to TLV, I will not describe it here. Because the TLV protocol in the project also involves some packet header and Verification Code considerations, this article will skip these considerations and talk about the transmission of core data packets TLV.

 

Specific ideas

1. Create a solution TLVSocketDemo.

 

2. Create the project TLVSocketDemo. Server. This project serves as the basic class library of the Server, including some AppServer and AppSession extensions. Of course, SuperSocket provides a project named "SocketService", which is a container that allows the AppServer to run in it. Therefore, you need to copy some SocketService-related files to the generated output directory.

 

3. Subclass Implementation of AppServer:

Public class TLVProtocolServer: AppServer
{
Public TLVProtocolServer ()
: Base (new TLVProtocol ())
{

}
}

 

4. Subclass Implementation of AppSession:

Public class TLVProtocolSession: AppSession
{
Public override void HandleExceptionalError (Exception e)
{

}
}

 

5. TLVEntityListCommandInfo is a command entity class received by the server. This class must inherit from CommandInfo:

Public class TLVEntityListCommandInfo: CommandInfo>
{
Public TLVEntityListCommandInfo (string key, List data)
: Base (key, data)
{

}
}

In fact, TLVEntity is a entity structure of TLV. Implementation of the TLVEntity class:

[Serializable]
///
/// TLV entity
///
Public class TLVEntity
{
///
/// Mark
///
Public byte [] Tag {get; set ;}

///
/// Data Length
///
Public byte [] Length {get; set ;}

///
/// Data
///
Public byte [] Value {get; set ;}

///
/// Mark the number of bytes occupied
///
Public int TagSize {get; set ;}

///
/// Data Length in bytes
///
Public int LengthSize {get; set ;}

///
/// Subnested TLV entity
///
Public TLVEntity Sub_TLVEntity {get; set ;}
}

 

6. custom protocol: TLVProtocol. cs, inherited from the standard interface of ICustomProtocol:

Public class TLVProtocol: ICustomProtocol
{
Public ICommandReader CreateCommandReader (IAppServer appServer)
{
Return new TLVCommandReader (appServer );
}
}

You can use the CreateCommandReader method to obtain the reading method of byte array data.

 

TLVCommandReader is mainly used for Command Parsing.

Public class TLVCommandReader: CommandReaderBase
{
Public TLVCommandReader (IAppServer appServer)
: Base (appServer)
{

}

Public override TLVEntityListCommandInfo FindCommandInfo (IAppSession session, byte [] readBuffer, int offset, int length, bool isReusableBuffer, out int left)
{
Left = 0;

AddArraySegment (readBuffer, offset, length, isReusableBuffer );

Byte [] source = BufferSegments. ToArrayData ();

List list = TLVPackage. Construct (source );

Return new TLVEntityListCommandInfo ("ECHO", list );
}
}
}

Note that the FindCommandInfo method can read byte array data and construct TLV entities.

The implementation of TLVPackage. Construct is mentioned in the previous article.

 

7. Compile the command class:

Public class ECHO: CommandBase
{
Public override void ExecuteCommand (TLVProtocolSession session, TLVEntityListCommandInfo commandInfo)
{
String data = BinaryUtil. BinarySerialize (commandInfo. Data );
Session. SendResponse (data );
}
}

The data sent to the client is first serialized and base64-encoded by the List <Entity> List. Send the message to the client through SendResponse.

 

8. modify the configuration of the supersocket.socketservice.exe. configTLV service.

 

9th, after the project is generated, the project destination is output to the corresponding directory of supersocket.socketserver.exe. After the compilation is passed, the TLV Service server has been written. Is it easy.

 

10. Create a Client program for TLVSocketDemo. Client:

Static int port = 911;
Static void Main (string [] args)
{
EndPoint serverAddress = new IPEndPoint (IPAddress. Parse ("127.0.0.1"), port );

Using (Socket socket = new Socket (serverAddress. AddressFamily, SocketType. Stream, ProtocolType. Tcp ))
{
Socket. Connect (serverAddress );

Byte [] data = new byte [0];
Using (FileStream stream = new FileStream (Application. StartupPath + "\ tlvdata. dat", FileMode. Open, FileAccess. Read ))
{
Using (BinaryReader reader = new BinaryReader (stream ))
{
Reader. BaseStream. Seek (0, SeekOrigin. Begin );
Data = reader. ReadBytes (int) reader. BaseStream. Length );
}
}

Socket. Send (data, data. Length, SocketFlags. None );

Byte [] temp = new byte [1, 5000];

Int read = socket. Receive (temp, 0, 5000, SocketFlags. None );

Byte [] response = new byte [read];
Array. Copy (temp, 0, response, 0, read );

String responseText = Encoding. ASCII. GetString (response );

List list = BinaryUtil. BinaryDeserialize> (responseText );

Console. WriteLine ("the server has constructed {0} TLV structures.", list. Count );

Console. ReadKey ();
}
}

Here, we will explain that we can read the byte array data through the tlvdata. dat file and then send the data to the server. After the server completes processing, it will return the data to the client, and a Base64 encoding will be returned. Then compile the Client code.

 

11. Run the program first. socketService service, you can open RunServer directly. bat, or you can use InstallService. bat to install Windows Services; then run the client program TLVSocketDemo. client:

Server:

Client:

It indicates that the server has constructed two TLV structures for the TLV byte array data. The Data of CommandInfo can be obtained through the ExecuteCommand parameter, which is List <TLVEntity>.

 

Summary: the extension of the SuperSocket custom protocol is still very easy to use. You can also use this extension method to customize your own application protocol.

The Demo source code of the Server and Client is attached: TLVSocketDemo.rar

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.