Brief Analysis of Flash socket principles and implementation of Flash Client Network Layer

Source: Internet
Author: User

Keywords as3 flash .net. Socket tcpclient

Reprinted Please note: http://blog.csdn.net/herm_lib/article/details/8245698

The Network Layer introduced here includes two small modules: tcpclient implemented by flash.net. socket and dispatcher that sends messages to the target handler according to the command ID. The upper-layer logic registers the handler of the processing logic to the dispatcher at the network layer to process received messages in the handler.

Let's talk about some common knowledge about networks. Generally, the packet is called packet on the IP layer, the TCP on the transport layer is called segment, and UDP is called datasync. Many RFC descriptions on the application layer are described as message. Message: we can see the message packages corresponding to the application protocol. There are various RFC protocol specifications and Message format descriptions. The TCP data received by the application layer from the TCP layer is based on the stream. What is the stream? That is, the protocol data at the application layer is mixed together (Unclear ). Flash .net. Socket finally gave us this stream.

Briefly describe the implementation principle of flash.net. socket.

This socket is a brief encapsulation of tcp client functions. The client functions include creating a socket handle, connect, and responding to a callback notification when receiving data, there are also important connection close and various error callback notifications.

The socket maintains two queues, one is the buffer for receiving data, and the other is the buffer for sending data. Our application is to interact with the two buffers to send and receive data.

When the socket receives data, it first puts the data into its receiving buffer; then it sends a progressevent event to the application; when the application receives the event, it can try to fetch data from the receiving buffer.

When the application sends data, it puts the data into the buffer sent inside the socket. After flush is called, the data sent to the buffer will be sent out.

After preliminary tests, it is almost certain that the data received by the network is stored in the receiving buffer inside the socket and the data sent in the buffer inside the socket is transmitted to the network, the driver thread is different from the thread of our application. The basic principle of socket. Flush () is to send a write network event notification to the internal interface that sends data to the network.

Use an independent thread to send and receive data from the bottom layer of the network. The handler at the logic layer follows its own thread. This design is reasonable (the handler thread in the network library design is the same as the network thread ). My Herm design is similar. The logic layer uses its own thread, and the network layer can start multiple threads.

For more information, see Herm. Http://blog.csdn.net/herm_lib/article/details/5980657

Next, let's discuss how to implement the flash tcp client.

Flash.net. the socket object gives us a TCP stream. The main thing we need to do is to break this stream into messages that our application can understand. The message format is determined by our application. For example, a simple protocol message is defined as follows:

Total_msg_len | ----- msg_data ----- |

Total_msg_len

It is defined as four bytes. Normally, it is defined as the network byte order (big-Endian). The four bytes indicate the length of the entire message (which can include total_msg_len itself ).

Msg_data

The protocol message data required by our protocol is determined by the application developer. The format can be binary, XML, Jason, protobuf, and so on.

The simple implementation of tcpclient is like the following:

Public class tcpclient {private VaR _ Sock: socket; private VaR _ totalmsglen: uint; private VaR _ handlebuf: bytearray; private VaR _ msgdispatcher: msgdispatcher; Public Function tcpclient (sockstatereportor: Function) {_ sock = new socket (); _ totalmsglen = 0; _ handlebuf = new bytearray (); _ sock. addeventlistener (progressevent. socket_data, onsocketdata);} private function onsocketdata (Event: progressevent): void {While (true) {If (! Handlesocketdata () break;} private function handlesocketdata (): Boolean {If (_ sock. bytesavailable <= msg_len_size) // msg_len_size = 4. The data does not exceed the total length. If (_ totalmsglen = 0) _ totalmsglen = _ sock. readunsignedint (); // The total length of the first read // The buffer data received by the socket has not reached the length required for the protocol message. First, return, if (_ totalmsglen-msgdef. msg_len_size> _ sock. bytesavailable) return false; _ handlebuf. clear (); // use _ handlebuf repeatedly. Clear _ sock when using it. readbytes (_ handlebuf, 0, _ totalmsglen-msg_len_size); _ msgdispatcher. dispatch (_ handlebuf, _ handlebuf. length); // The data is distributed to the registered handler _ totalmsglen = 0; return true ;}}

Note that _ sock. readunsignedint () is in the byte sequence. For details, see as3 socket.

The Code should be clear. If the socket supports peek data (only copying data from the buffer, internal buffer does not clear data), this will be clearer, and _ totalmsglen does not need to be saved.

The logic layer code is similar to the following:

public class Auth {private var _tcpClient:TCPClient;public function Auth(tcpClient:TCPClient) {_tcpClient = tcpClient;tcpClient.msgDispatcher.register(CmdType.CT_AUTH, CmdCodeAuth.CC_AUTH_SIGN_RES, onAuthRes);}private function onAuthRes(mb:MsgBody):void{}}

Register Auth: onauthres to msgdispatcher in tcpclient. After receiving the corresponding message, it will be processed in onauthres.

For implementation of msgdispatcher, refer to as3 msgdispatcher in the following article: Comparison of the callback mechanism based on boost: function/bind and as3 Functions

Tcpclient sends messages with a total length of 4 bytes at the time of sending. Pay attention to the byte sequence agreed by both parties before sending the message data.

The rest are closed and various error event responses.

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.