CN113626208B - Server communication method based on NIO asynchronous thread model - Google Patents
Server communication method based on NIO asynchronous thread model Download PDFInfo
- Publication number
- CN113626208B CN113626208B CN202010384613.5A CN202010384613A CN113626208B CN 113626208 B CN113626208 B CN 113626208B CN 202010384613 A CN202010384613 A CN 202010384613A CN 113626208 B CN113626208 B CN 113626208B
- Authority
- CN
- China
- Prior art keywords
- defining
- state
- server
- message
- event
- Prior art date
- Legal status (The legal status is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the status listed.)
- Active
Links
- 238000000034 method Methods 0.000 title claims abstract description 77
- 230000006854 communication Effects 0.000 title claims abstract description 68
- 238000004891 communication Methods 0.000 title claims abstract description 64
- 238000012545 processing Methods 0.000 claims abstract description 56
- 238000012544 monitoring process Methods 0.000 claims abstract description 13
- 230000006870 function Effects 0.000 claims description 58
- 230000004044 response Effects 0.000 claims description 25
- 230000008569 process Effects 0.000 claims description 16
- 239000000872 buffer Substances 0.000 claims description 14
- 230000000903 blocking effect Effects 0.000 claims description 11
- 238000012790 confirmation Methods 0.000 claims description 11
- 238000012937 correction Methods 0.000 claims description 10
- 238000013507 mapping Methods 0.000 claims description 6
- 230000005856 abnormality Effects 0.000 claims description 4
- 230000003068 static effect Effects 0.000 claims description 4
- 238000005265 energy consumption Methods 0.000 claims description 3
- 230000001960 triggered effect Effects 0.000 claims description 3
- 238000010926 purge Methods 0.000 claims 1
- 238000011084 recovery Methods 0.000 description 11
- 238000005516 engineering process Methods 0.000 description 6
- 238000010586 diagram Methods 0.000 description 4
- 230000001133 acceleration Effects 0.000 description 2
- 238000012986 modification Methods 0.000 description 2
- 230000004048 modification Effects 0.000 description 2
- 230000009286 beneficial effect Effects 0.000 description 1
- 230000005540 biological transmission Effects 0.000 description 1
- 238000011161 development Methods 0.000 description 1
- 230000000694 effects Effects 0.000 description 1
- 230000007613 environmental effect Effects 0.000 description 1
- 238000004880 explosion Methods 0.000 description 1
- 238000005111 flow chemistry technique Methods 0.000 description 1
- 230000006872 improvement Effects 0.000 description 1
- 230000007246 mechanism Effects 0.000 description 1
- 238000010187 selection method Methods 0.000 description 1
Classifications
-
- G—PHYSICS
- G06—COMPUTING; CALCULATING OR COUNTING
- G06F—ELECTRIC DIGITAL DATA PROCESSING
- G06F9/00—Arrangements for program control, e.g. control units
- G06F9/06—Arrangements for program control, e.g. control units using stored programs, i.e. using an internal store of processing equipment to receive or retain programs
- G06F9/46—Multiprogramming arrangements
- G06F9/54—Interprogram communication
- G06F9/544—Buffers; Shared memory; Pipes
-
- G—PHYSICS
- G06—COMPUTING; CALCULATING OR COUNTING
- G06F—ELECTRIC DIGITAL DATA PROCESSING
- G06F9/00—Arrangements for program control, e.g. control units
- G06F9/06—Arrangements for program control, e.g. control units using stored programs, i.e. using an internal store of processing equipment to receive or retain programs
- G06F9/46—Multiprogramming arrangements
- G06F9/50—Allocation of resources, e.g. of the central processing unit [CPU]
- G06F9/5061—Partitioning or combining of resources
-
- G—PHYSICS
- G06—COMPUTING; CALCULATING OR COUNTING
- G06F—ELECTRIC DIGITAL DATA PROCESSING
- G06F9/00—Arrangements for program control, e.g. control units
- G06F9/06—Arrangements for program control, e.g. control units using stored programs, i.e. using an internal store of processing equipment to receive or retain programs
- G06F9/46—Multiprogramming arrangements
- G06F9/54—Interprogram communication
- G06F9/542—Event management; Broadcasting; Multicasting; Notifications
-
- G—PHYSICS
- G16—INFORMATION AND COMMUNICATION TECHNOLOGY [ICT] SPECIALLY ADAPTED FOR SPECIFIC APPLICATION FIELDS
- G16Y—INFORMATION AND COMMUNICATION TECHNOLOGY SPECIALLY ADAPTED FOR THE INTERNET OF THINGS [IoT]
- G16Y10/00—Economic sectors
- G16Y10/35—Utilities, e.g. electricity, gas or water
-
- G—PHYSICS
- G16—INFORMATION AND COMMUNICATION TECHNOLOGY [ICT] SPECIALLY ADAPTED FOR SPECIFIC APPLICATION FIELDS
- G16Y—INFORMATION AND COMMUNICATION TECHNOLOGY SPECIALLY ADAPTED FOR THE INTERNET OF THINGS [IoT]
- G16Y30/00—IoT infrastructure
-
- G—PHYSICS
- G16—INFORMATION AND COMMUNICATION TECHNOLOGY [ICT] SPECIALLY ADAPTED FOR SPECIFIC APPLICATION FIELDS
- G16Y—INFORMATION AND COMMUNICATION TECHNOLOGY SPECIALLY ADAPTED FOR THE INTERNET OF THINGS [IoT]
- G16Y40/00—IoT characterised by the purpose of the information processing
- G16Y40/10—Detection; Monitoring
-
- G—PHYSICS
- G06—COMPUTING; CALCULATING OR COUNTING
- G06F—ELECTRIC DIGITAL DATA PROCESSING
- G06F2209/00—Indexing scheme relating to G06F9/00
- G06F2209/50—Indexing scheme relating to G06F9/50
- G06F2209/5011—Pool
-
- G—PHYSICS
- G06—COMPUTING; CALCULATING OR COUNTING
- G06F—ELECTRIC DIGITAL DATA PROCESSING
- G06F2209/00—Indexing scheme relating to G06F9/00
- G06F2209/50—Indexing scheme relating to G06F9/50
- G06F2209/5018—Thread allocation
Landscapes
- Engineering & Computer Science (AREA)
- Software Systems (AREA)
- Theoretical Computer Science (AREA)
- Computing Systems (AREA)
- Physics & Mathematics (AREA)
- General Engineering & Computer Science (AREA)
- General Physics & Mathematics (AREA)
- Multimedia (AREA)
- Accounting & Taxation (AREA)
- Development Economics (AREA)
- Economics (AREA)
- General Business, Economics & Management (AREA)
- Business, Economics & Management (AREA)
- Computer And Data Communications (AREA)
Abstract
The invention discloses a server communication method based on an NIO asynchronous thread model, which adopts the NIO asynchronous thread model, so that a great amount of connection management can be completed through one thread, thereby improving the communication performance of the server, enabling the communication process of the server and a client to be more efficient and flexible and occupying less resources. The specific content of the communication method comprises the steps of carrying out initialization definition setting in a framework and establishing a connection request. And starting socket service, starting monitoring, processing various events after the system receives the notification of the appointed event message, and initializing to clear the event after processing. The communication method has clear logic and is easy to realize; the occupied resources are few, and the method is efficient and flexible; the real-time performance is strong, and the method is stable and reliable.
Description
Technical Field
The invention relates to the technical field of servers, in particular to a server communication method based on an NIO asynchronous thread model.
Background
With the massive application and rapid development of IOT technology, a large number of network applications deployed at terminal devices access the internet with TCP/IP (transmission control protocol/internet protocol). In modern times, millions of internet of things devices are connected in a digital city, and the devices are not in communication at any time, so that the terminal data size is huge. The Socket communication mode is a common mechanism, has very strong applicability, and can be used for network communication, hardware control, inter-process communication and other occasions. Socket is a Socket used for describing an IP address and a port, is a handle of network communication, and is usually long in running time, sensitive to environmental changes and complex in concurrent control. Therefore, how to ensure stable and efficient Socket communication is a very important issue. When dealing with such huge numbers of Socket connections, the conventional Socket processing technology cannot meet the actual requirements, and a server needs to introduce a new and more efficient technology to process each connection in parallel.
In the traditional communication mode, IO is blocked, and a blocking IO multithreading model combines the related blocking operation of Socket with multithreading for communication, and is characterized in that each thread can process a single connection for receiving and transmitting data, and each new connection is processed by a new dynamically created thread. The method has the advantages that the logic of each thread is clear and the division of the work is clear, but the throughput of service can be affected when the number of threads is too small, and when the number of the threads generated by the connection of the client is increased exceeds the bearing capacity of the CPU, the occupancy rate of the CPU and the memory resources is high, a large amount of system resources are consumed to influence the system performance, and the instantaneity and the stability are reduced.
3-5, NIO has the biggest characteristic of optimizing the use of threads compared with the traditional IO model, and adopts an event-driven model, so that one thread can be used for managing a plurality of socket handles through a selector. The selector multiplexing thread model also has the characteristics of less occupied resources, high efficiency, flexibility and the like on the basis of the advantages of the traditional communication mode, and is therefore used for a plurality of special communication servers. The NIO technology improves the traditional one-to-one network service model into one-to-many, namely one server I/O thread simultaneously manages a plurality of client connections, which greatly reduces the number of server threads, and simultaneously reduces the creation frequency of the server threads due to the application of the thread pool technology, thereby greatly reducing the cost of switching between I/O threads of a server system, improving the effective utilization rate of resources of the server system and fundamentally optimizing the network application performance of the system. With the progress of modernization, data explosion grows, and the use of the original equipment monitoring system program has not been able to meet the ever-increasing number of equipment.
Disclosure of Invention
In order to provide a communication method with clear logic and less occupied resources, the invention provides a non-blocking communication method using an NIO asynchronous thread model, and the non-blocking communication method is deployed on a non-invasive network platform server, so that the communication performance of the server is improved, the communication process between the server and a client is more efficient and flexible, and the occupied resources are less.
In order to achieve the above object, the present invention provides a server communication method based on an NIO asynchronous thread model, including:
Initializing definition settings, comprising: defining private character set variables of the buffer zone, and assigning the decoding buffer as a character set of the utf-8 type; defining a setting selector (selector) as a listener; defining a mapping client channel (channel), and defining a client Map set as an unordered set of static hash table (HashMap) types for key value pairs;
the client establishes a connection request;
Starting a socket service by a server, and starting a monitor to monitor; when the event message is monitored, a new thread is opened, the monitored event is obtained, the event is processed, and the event after processing is cleared.
Further, starting the monitor to monitor includes:
opening a server communication channel;
setting the communication channel to non-blocking;
a communication channel acquisition socket (socket);
binding a server port number;
opening the monitor by an open method;
Registering the communication channel with a selector by a registration (register) method and using a receiving connection of a selection key class (SelectionKey) for attributes to indicate that the client connection is monitored by the server, which can receive the connection;
calling an open (open) method to open the monitor;
when the server receives a connection request from the client, a receive connection progress event is triggered.
Further, the method comprises defining handle method processing event, initializing server communication channel, socket channel, receiving information variable, and assigning the three as null; the method also comprises the steps of judging whether the selection key class (SelectionKey) is receivable, if yes, connecting a client, and registering the communication channel to be readable; if the data is not receivable, judging whether the selection key class (SelectionKey) is readable, if so, reading the response of the server and reading the data of the cache area; if the input and output abnormality is unreadable, the input and output abnormality is thrown out, and the initial state is returned.
Further, the process of processing the event includes:
(1) Reading client data;
(2) Judging whether the byte of the read message is normal or not, if not, continuing monitoring; if so, entering a step (3);
(3) Analyzing the equipment ID number, judging whether the equipment ID number exists in the cache, and if so, entering the step (4); if not, adding the client connection corresponding to the equipment ID number into a cache, and entering a step (4);
(4) Judging whether the message CRC check is successful or not, if not, continuing monitoring; if successful, the message type is resolved and the corresponding operation is executed.
Further, the clearing event includes:
In the new thread, the selection key class (SelectionKey) is cleared by calling a clear method, in the clearing process, the selector serves as a message listener and is responsible for monitoring the event registered by a channel (channel) in the server, and when the registered event occurs, the corresponding thread is called for processing.
Further, the alarm process is completed by defining doProcessAlarm functions, and the flow is as follows:
(1) Defining a sixth byte of read data as an error type et (error type);
(2) Judging the error type, and if et=1, sending out an overcurrent alarm; if et=2, a temperature alarm is sent out;
(3) Setting the on-line state of the equipment, and sending an alarm short message to the user.
(4) The error message is inserted into the device alarm statistics table.
Further, defining doProcessCancelAllTiming a function to complete the terminal to cancel all timing reply processing functions includes: defining a response state from the sixth byte of the read data, setting the device receiving state as successful in receiving the data if the value of the response state is '0', otherwise setting the receiving state as illegal in receiving the data field;
Defining doProcessCancelTiming a function to complete a terminal timing configuration cancellation reply processing function, including: defining a response state from the sixth byte of the read data, setting the receiving state to be successful if the value of the response state is '6', otherwise setting the receiving state to be illegal in receiving the data field;
defining doProcessTimingConfiguration a function to complete a terminal timing configuration reply processing function, including: defining a response state from the sixth byte of the read data, setting the receiving state to be successful if the value of the response state is '6', setting the receiving state to be a timing configuration receiving exceeding range if the value of the response state is '5', and indicating that the receiving state is a data domain illegality and a giving state is needed if the values of the response state are not '5' and '6';
Defining doProcessTimeCalibration a function to complete a terminal time correction reply processing function, including: inserting information into the log "terminal time correction confirmation process, device correction success-! "and corrected device number, while setting the reception of the device to be successful.
Further, defining doProcessSwitchControl functions to complete the reply processing of the terminal switch, and updating the database functions, including: firstly updating a database, selecting a new device from a device list, judging whether the device list is empty, if so, prompting a warning that a switch confirms that the processing is not carried out, and returning; if the device is not empty, the switch state of the device is continuously set, meanwhile, the update time of the device is set, the database mapping file of the device is updated, and then the switch confirmation processing of the information is recorded, wherein the update of the state of the device is successful.
Further, defining doProcessHeartbeat functions to complete the processing function of the heartbeat message of the terminal includes: defining the switching state of the equipment in the heartbeat message; defining 'year', 'month', 'day', 'hour', 'minute', 'second' 6 numbers representing the last update time of the device; defining 5 electrical quantities of 'voltage', 'current', 'active power', 'reactive power' and 'electric energy consumption' calculated by using the 'active power', wherein the 5 electrical quantities represent the electrical state of the device; defining a current temperature value of the device; and then updating a database of the new equipment in the equipment list by using the information, and finally sending a confirmation message xx equipment analysis heartbeat message.
Further, defining confirmHearBeatProcess a function to complete the function of sending heartbeat acknowledgment messages includes: defining an octet array, generating a CRC-16 check value array by using the octet array and the received data, wherein the array length is '4' or '2', otherwise prompting: "failure to parse heartbeat message generates CRC value failure".
The technical scheme of the invention has the following beneficial technical effects:
The invention discloses a non-blocking server communication method based on an NIO asynchronous thread model, wherein a server is applied to a non-invasive network platform system and is responsible for communication with non-invasive power equipment to acquire power information of a power load. In order to support high performance and improve the real-time performance and stability of communication, the communication framework adopts an NIO asynchronous non-blocking communication mode, and the specific content of the communication method comprises registering all communication events and callback functions to the framework, establishing a connection request and performing Socket read-write operation. The communication mode does not need to create threads and poll Socket states, after the system receives the notification of the appointed event message, connection is established with the client through the accept function, and the thread callback registration function is multiplexed from the thread pool to asynchronously interact with the user. The mode can ensure strict data receiving and transmitting sequence, meanwhile, the logic is clear, the occupied resources are less, and the mode is efficient and flexible; the logic is clear and easy to realize; the occupied resources are small; the real-time performance is strong, and the method is stable and reliable.
Drawings
FIG. 1 is a flow chart of processing events;
FIG. 2 is a logic flow diagram of a server and device terminal communication program;
FIG. 3 is a schematic diagram of a NIO model;
FIG. 4 is a schematic diagram of a server multithreading architecture;
FIG. 5 is a select multiplexing model IO flow diagram.
Detailed Description
The objects, technical solutions and advantages of the present invention will become more apparent by the following detailed description of the present invention with reference to the accompanying drawings. It should be understood that the description is only illustrative and is not intended to limit the scope of the invention. In addition, in the following description, descriptions of well-known structures and techniques are omitted so as not to unnecessarily obscure the present invention.
The NIO technology consists mainly of three core parts, including: buffer, channel, selector. The Channel is a Channel capable of reading and writing data in two directions, and comprises file operation IO and network IO, namely FILECHANNEL (file IO), DATAGRAMCHANNEL (udp datagram), socketChannel (tcp client) and ServerSocketChannel (tcp server). Buffer is an intermediate Buffer from which data can be read to Buffer or vice versa. By using Buffer, the system can directly open up the memory in the memory to perform data operation, thereby reducing IO duplication operation and improving IO operation efficiency. The Buffer includes basic data type buffers such as ByteBuffer, charBuffer, intBuffer, file memory map buffers, and direct memory area buffers. While a Selector implements the handling of multiple channels by a single thread. The Selector is first established by the open method, then registered to the Channel, and after registration, the Selector waits for a request by the select method. When the select request has a time parameter and an operation request is received within the wait time, the number of operable requests is returned, otherwise a timeout is prompted. When the select request incoming parameter is 0 or is a parameter-free method, then the request is responded to using the blocking mode. The system, upon receipt of the request, calls SELECTEDKEYS back to the collection of SelectionKey, selectionKey saves the channels and selectors that handle the current request and provides four different operation types, namely, selectionKey.OP_ CONNECT, selectionKey.OP _ ACCEPT, selectionKey.OP _ READ, selectionKey.OP _WRITE.
With reference to fig. 1, the server communication method based on the NIO asynchronous thread model deployed on the present non-invasive system server includes the following steps:
1. The definition settings are initialized. The method specifically comprises the following steps:
(1) Decoding buffer: defining private character set variables of the cache region, and assigning the private character set variables as follows: the utf-8 type character set, which can be used to represent any character in the Unicode standard.
(2) Definition of selector: a private static type variable Selector is defined as a Selector listener in the communication framework.
(3) Mapping client channel: the client Map </SUB > set is defined as an unordered set of static HashMap </SUB > types and is used for storing Key-Value Key Value pairs of a character string-communication channel.
2. The client establishes a connection request.
3. And the server starts socket service, and starts a monitor to monitor. The method specifically comprises the following steps:
(1) Calling an open method to open a server communication channel ServerSocketChannel;
(2) The communication channel invokes configureBlocking a method and sets the incoming parameters to false and the channel to non-blocking;
(3) Calling a socket method by a communication channel to obtain a socket;
(4) The server socket call bind method binds the port number of the server, and obtains the IP address (host name) and the port number through the InetSocketAddress class;
(5) Opening a monitor by an open method;
(6) The communication channel calls a register method to register on a monitor selector, and meanwhile, a connection proceeding event is received by adopting a SelectionKey.OP_ ACCEP event processing flow, when a server receives a connection request of a client, the SelectionKey.OP_ACCEPT is triggered to indicate that the server monitors the connection of the client, and the server can receive the connection.
In this process, the listener will listen until the client has requested it and then enter the corresponding event processing.
The process of starting monitoring comprises the following steps:
Judging whether a new event occurs or not, and if the new event does not occur, blocking the selection method all the time; if so, a new thread is opened up to acquire the monitored event. The select method blocks until a related event occurs or times out.
4. Processing an event: defining a handle method processing event, initializing a server communication channel, a socket channel and a received information variable, and assigning the three as null; judging selectionKey whether the selection key class is receivable or not, if yes, connecting a client, and registering the communication channel to be readable; if the data is not receivable, judging selectionKey whether the data is readable, if so, reading the response of the server and reading the data of the cache area; if the data is unreadable, returning to the initial state.
5. The processed event is cleared in preparation for processing the next event. With reference to fig. 2, the server and device terminal communication program logic connects the ali cloud server background with a plurality of client devices by using an NIO server asynchronous thread method, so that the server can process information of a plurality of devices at the same time, thereby improving the communication performance of the server. The event flow processing comprises the following steps:
(1) Reading client data;
(2) Judging whether the byte of the read message is normal or not, if not, continuing monitoring; if so, entering a step (3);
(3) Analyzing the equipment ID number, judging whether the equipment ID number exists in the cache, and if so, entering the step (4); if not, adding the client connection corresponding to the equipment ID number into a cache, and entering a step (4);
(4) Judging whether the message CRC check is successful or not, if not, continuing monitoring; if successful, the message type is resolved and the corresponding operation is executed.
The clearing of the processed event includes:
In the new thread, selectionKeys call clear method is cleared. In the process, the selector acts as a listener of the message and is responsible for monitoring the event registered by the channel, so that a large number of connections can be managed through one thread, and when the registered event occurs, the corresponding thread is called for processing. Thus, one thread is not needed for each connection to maintain the long connection, the overhead of the long connection is reduced, and the context switching is reduced, so that the throughput of the system is improved.
In addition, the server communication method also comprises other event processing functions, including: the method comprises the following functions of temperature and overcurrent alarm processing, terminal cancellation of all timing recovery processing, terminal timing configuration cancellation recovery processing, terminal data uploading speed recovery processing, terminal data uploading acceleration recovery processing, terminal timing configuration recovery processing, terminal time correction recovery processing, terminal switch recovery processing, database updating, terminal heartbeat message processing and heartbeat confirmation message sending. The specific implementation of these functions is as follows:
the alarm process is finished by defining doProcessAlarm functions, and the flow is as follows:
1. The sixth byte of the read data is defined as error type (hereinafter abbreviated as et).
2. And judging the error type. If et=1, an overcurrent alarm is sent out; if et=2, a temperature alarm is issued.
3. Setting the on-line state of the equipment, and sending an alarm short message to the user (if the time is less than five minutes from the last alarm, the short message is not sent repeatedly).
4. The error message is inserted into the device alarm statistics table.
Defining doProcessCancelAllTiming a function to finish the terminal to cancel all timing recovery processing functions, specifically as follows: and defining a response state from the sixth byte of the read data, setting the device receiving state as successful in receiving the data if the value of the response state is 0, and otherwise setting the receiving state as illegal in receiving the data field of the data.
Defining doProcessCancelTiming a function to complete the terminal timing configuration cancellation reply processing function, similar to doProcessCancelAllTiming function above, if the value of the response state is '6', setting the receiving state to be successful, otherwise, illegal data domain receiving is achieved.
Defining doProcessDataSpeedRecovery a function to complete a recovery processing function of the terminal data uploading speed, defining doProcessDataAcceleration a function to complete a recovery processing function of the terminal data uploading acceleration, and defining doProcessTimingConfiguration a function to complete a recovery processing function of the terminal timing configuration, wherein like the two functions, if the value of the response state is '6', the receiving state is set to be successful, if the value of the response state is '5', the receiving state is set to be the timing configuration receiving exceeding range, and if the values of the response state are not '5' and '6', the illegal data domain is indicated, and the state needs to be given. Defining doProcessTimeCalibration a function to complete a terminal time correction reply processing function, wherein the specific content is as follows: inserting information into the log "terminal time correction confirmation process, device correction success-! "and corrected device number, while setting the reception of the device to be successful. Defining doProcessSwitchControl functions to complete terminal switch reply processing and update database functions, and specifically comprises the following steps: firstly updating a database, selecting a new device from a device list, judging whether the device list is empty, if so, prompting a warning that a switch confirms that the processing is not carried out, and returning. If the device is not empty, the switch state of the device is continuously set, meanwhile, the update time of the device is set, the database mapping file of the device is updated, and then the switch confirmation processing of the information is recorded, wherein the update of the state of the device is successful. Defining doProcessHeartbeat functions to complete the processing function of the heartbeat message of the terminal, wherein the specific functions are realized as follows: defining the switching state of the equipment in the heartbeat message; defining 'year', 'month', 'day', 'hour', 'minute', 'second' 6 numbers representing the last update time of the device; defining 5 electrical quantities of 'voltage', 'current', 'active power', 'reactive power' and 'electric energy consumption' calculated by using the 'active power', wherein the 5 electrical quantities represent the electrical state of the device; defining a current temperature value of the device; and then updating a database of the new equipment in the equipment list by using the information, and finally sending a confirmation message xx equipment analysis heartbeat message.
Defining confirmHearBeatProcess a function to complete the function of sending heartbeat confirmation messages, wherein the specific process is as follows: defining an octet array of eight bits and using it and the received data to generate an array of CRC-16 check values, the array length being either '4' or '2', otherwise prompting: "failure to parse heartbeat message generates CRC value failure".
In summary, the invention discloses a server communication method based on an NIO asynchronous thread model, which adopts the NIO asynchronous thread model, so that a great amount of connection management can be completed through one thread, thereby improving the communication performance of the server, enabling the communication process between the server and a client to be more efficient and flexible, and occupying less resources. The specific content of the communication method comprises the steps of carrying out initialization definition setting in a framework and establishing a connection request. And starting socket service, starting monitoring, processing various events after the system receives the notification of the appointed event message, and initializing to clear the event after processing. The communication method has clear logic and is easy to realize; the occupied resources are few, and the method is efficient and flexible; the real-time performance is strong, and the method is stable and reliable.
It is to be understood that the above-described embodiments of the present invention are merely illustrative of or explanation of the principles of the present invention and are in no way limiting of the invention. Accordingly, any modification, equivalent replacement, improvement, etc. made without departing from the spirit and scope of the present invention should be included in the scope of the present invention. Furthermore, the appended claims are intended to cover all such changes and modifications that fall within the scope and boundary of the appended claims, or equivalents of such scope and boundary.
Claims (7)
1. A server communication method based on an NIO asynchronous thread model, comprising:
Initializing definition settings, comprising: defining private character set variables of the buffer zone, and assigning the decoding buffer as a character set of the utf-8 type; defining a setting selector (selector) as a listener; defining a mapping client channel (channel), and defining a client Map set as an unordered set of static hash table (HashMap) types for key value pairs;
the client establishes a connection request;
Starting a socket service by a server, and starting a monitor to monitor; when the event message is monitored, a new thread is opened, the monitored event is obtained, the event is processed, and the event after processing is cleared;
starting the monitor to monitor comprises the following steps:
opening a server communication channel;
setting the communication channel to non-blocking;
a communication channel acquisition socket (socket);
binding a server port number;
opening the monitor by an open method;
Registering the communication channel with a selector by a registration (register) method and using a receiving connection of a selection key class (SelectionKey) for attributes to indicate that the client connection is monitored by the server, which can receive the connection;
calling an open (open) method to open the monitor;
when the server receives a connection request of the client, a connection proceeding event is received and triggered;
The flow of processing the event comprises:
(1) Reading client data;
(2) Judging whether the byte of the read message is normal or not, if not, continuing monitoring; if so, entering a step (3);
(3) Analyzing the equipment ID number, judging whether the equipment ID number exists in the cache, and if so, entering the step (4); if not, adding the client connection corresponding to the equipment ID number into a cache, and entering a step (4);
(4) Judging whether the message CRC check is successful or not, if not, continuing monitoring; if the message type is successful, analyzing the message type, and executing corresponding operation;
The purge event includes:
In the new thread, the selection key class (SelectionKey) is cleared by calling a clear method, in the clearing process, the selector serves as a message listener and is responsible for monitoring the event registered by a channel (channel) in the server, and when the registered event occurs, the corresponding thread is called for processing.
2. The server communication method based on the NIO asynchronous thread model of claim 1, comprising defining handle method processing events, initializing a server communication channel, a socket channel, receiving information variables, and assigning the three as null; the method also comprises the steps of judging whether the selection key class (SelectionKey) is receivable, if yes, connecting a client, and registering the communication channel to be readable; if the data is not receivable, judging whether the selection key class (SelectionKey) is readable, if so, reading the response of the server and reading the data of the cache area; if the input and output abnormality is unreadable, the input and output abnormality is thrown out, and the initial state is returned.
3. The NIO asynchronous thread model based server communication method of claim 1, wherein: the alarm process is finished by defining doProcessAlarm functions, and the flow is as follows:
(1) Defining a sixth byte of read data as an error type et (error type);
(2) Judging the error type, and if et=1, sending out an overcurrent alarm; if et=2, a temperature alarm is sent out;
(3) Setting the on-line state of equipment, and sending an alarm short message to a user;
(4) The error message is inserted into the device alarm statistics table.
4. The NIO asynchronous thread model based server communication method of claim 1, wherein:
Defining doProcessCancelAllTiming a function to complete the terminal to cancel all timing reply processing functions, including: defining a response state from the sixth byte of the read data, setting the device receiving state as successful in receiving the data if the value of the response state is '0', otherwise setting the receiving state as illegal in receiving the data field;
Defining doProcessCancelTiming a function to complete a terminal timing configuration cancellation reply processing function, including: defining a response state from the sixth byte of the read data, setting the receiving state to be successful if the value of the response state is '6', otherwise setting the receiving state to be illegal in receiving the data field;
defining doProcessTimingConfiguration a function to complete a terminal timing configuration reply processing function, including: defining a response state from the sixth byte of the read data, setting the receiving state to be successful if the value of the response state is '6', setting the receiving state to be a timing configuration receiving exceeding range if the value of the response state is '5', and indicating that the receiving state is a data domain illegality and a giving state is needed if the values of the response state are not '5' and '6';
Defining doProcessTimeCalibration a function to complete a terminal time correction reply processing function, including: inserting information into the log "terminal time correction confirmation process, device correction success-! "and corrected device number, while setting the reception of the device to be successful.
5. The NIO asynchronous thread model based server communication method of claim 1, wherein:
Defining doProcessSwitchControl a function to complete terminal switch reply processing and update database functions, including: firstly updating a database, selecting a new device from a device list, judging whether the device list is empty, if so, prompting a warning that a switch confirms that the processing is not carried out, and returning; if the device is not empty, the switch state of the device is continuously set, meanwhile, the update time of the device is set, the database mapping file of the device is updated, and then the switch confirmation processing of the information is recorded, wherein the update of the state of the device is successful.
6. The NIO asynchronous thread model based server communication method of claim 1, wherein:
Defining doProcessHeartbeat a function to complete a terminal heartbeat message processing function, including: defining the switching state of the equipment in the heartbeat message; defining 'year', 'month', 'day', 'hour', 'minute', 'second' 6 numbers representing the last update time of the device; defining 5 electrical quantities of 'voltage', 'current', 'active power', 'reactive power' and 'electric energy consumption' calculated by using the 'active power', wherein the 5 electrical quantities represent the electrical state of the device; defining a current temperature value of the device; and then updating a database of the new equipment in the equipment list by using the information, and finally sending a confirmation message xx equipment analysis heartbeat message.
7. The NIO asynchronous thread model based server communication method of claim 6, wherein:
Defining confirmHearBeatProcess a function to complete the function of sending heartbeat acknowledgment messages, including: defining an octet array, generating a CRC-16 check value array by using the octet array and the received data, wherein the array length is '4' or '2', otherwise prompting:
"failure to parse heartbeat message generates CRC value failure".
Priority Applications (1)
Application Number | Priority Date | Filing Date | Title |
---|---|---|---|
CN202010384613.5A CN113626208B (en) | 2020-05-08 | 2020-05-08 | Server communication method based on NIO asynchronous thread model |
Applications Claiming Priority (1)
Application Number | Priority Date | Filing Date | Title |
---|---|---|---|
CN202010384613.5A CN113626208B (en) | 2020-05-08 | 2020-05-08 | Server communication method based on NIO asynchronous thread model |
Publications (2)
Publication Number | Publication Date |
---|---|
CN113626208A CN113626208A (en) | 2021-11-09 |
CN113626208B true CN113626208B (en) | 2024-05-14 |
Family
ID=78377450
Family Applications (1)
Application Number | Title | Priority Date | Filing Date |
---|---|---|---|
CN202010384613.5A Active CN113626208B (en) | 2020-05-08 | 2020-05-08 | Server communication method based on NIO asynchronous thread model |
Country Status (1)
Country | Link |
---|---|
CN (1) | CN113626208B (en) |
Families Citing this family (2)
Publication number | Priority date | Publication date | Assignee | Title |
---|---|---|---|---|
CN114827035A (en) * | 2022-05-05 | 2022-07-29 | 浪潮通信信息系统有限公司 | Network element communication method, device and computer medium |
CN115914330B (en) * | 2022-10-11 | 2024-04-12 | 中国电子科技集团公司第二十八研究所 | Heterogeneous inter-application communication method based on NIO asynchronous thread model |
Citations (5)
Publication number | Priority date | Publication date | Assignee | Title |
---|---|---|---|---|
CN104917833A (en) * | 2015-06-08 | 2015-09-16 | 北京集奥聚合网络技术有限公司 | Asynchronous information processing method based on NIO request |
CN106254179A (en) * | 2016-08-05 | 2016-12-21 | 深圳先进技术研究院 | A kind of heartbeat packet asynchronous controlling method and device |
CN106850829A (en) * | 2017-02-28 | 2017-06-13 | 苏州星熙数据科技有限公司 | A kind of micro services design method based on non-blocking communication |
WO2019028673A1 (en) * | 2017-08-08 | 2019-02-14 | 深圳先进技术研究院 | B/s architecture-based data communication system and method, web server, and monitoring system |
CN110134534A (en) * | 2019-05-17 | 2019-08-16 | 普元信息技术股份有限公司 | The system and method for Message Processing optimization is carried out for big data distributed system based on NIO |
Family Cites Families (3)
Publication number | Priority date | Publication date | Assignee | Title |
---|---|---|---|---|
US7716339B2 (en) * | 2004-09-11 | 2010-05-11 | Oracle International Corporation | System and method for discretization of client-server interactions |
US20080133654A1 (en) * | 2006-12-01 | 2008-06-05 | Chei-Yol Kim | Network block device using network asynchronous i/o |
US20120089700A1 (en) * | 2010-10-10 | 2012-04-12 | Contendo, Inc. | Proxy server configured for hierarchical caching and dynamic site acceleration and custom object and associated method |
-
2020
- 2020-05-08 CN CN202010384613.5A patent/CN113626208B/en active Active
Patent Citations (5)
Publication number | Priority date | Publication date | Assignee | Title |
---|---|---|---|---|
CN104917833A (en) * | 2015-06-08 | 2015-09-16 | 北京集奥聚合网络技术有限公司 | Asynchronous information processing method based on NIO request |
CN106254179A (en) * | 2016-08-05 | 2016-12-21 | 深圳先进技术研究院 | A kind of heartbeat packet asynchronous controlling method and device |
CN106850829A (en) * | 2017-02-28 | 2017-06-13 | 苏州星熙数据科技有限公司 | A kind of micro services design method based on non-blocking communication |
WO2019028673A1 (en) * | 2017-08-08 | 2019-02-14 | 深圳先进技术研究院 | B/s architecture-based data communication system and method, web server, and monitoring system |
CN110134534A (en) * | 2019-05-17 | 2019-08-16 | 普元信息技术股份有限公司 | The system and method for Message Processing optimization is carried out for big data distributed system based on NIO |
Non-Patent Citations (2)
Title |
---|
一种高性能可靠服务器的设计与实现;潘思聪;;桂林航天工业学院学报(01);全文 * |
基于Java NIO开发高性能并发型服务器程序的研究;段艳明;肖辉辉;;软件导刊(05);全文 * |
Also Published As
Publication number | Publication date |
---|---|
CN113626208A (en) | 2021-11-09 |
Similar Documents
Publication | Publication Date | Title |
---|---|---|
Kovatsch et al. | Californium: Scalable cloud services for the internet of things with coap | |
US7992153B2 (en) | Queuing for thread pools using number of bytes | |
CN113626208B (en) | Server communication method based on NIO asynchronous thread model | |
US9172765B2 (en) | Polling-based secure network message notification system and method with performance enhancing features | |
US20230080588A1 (en) | Mqtt protocol simulation method and simulation device | |
TW202038581A (en) | Management client, and device monitoring system and method | |
US20130198265A1 (en) | Connection management in a computer networking environment | |
CN113596017B (en) | Protocol analysis method and device, soft gateway and storage medium | |
US20100146112A1 (en) | Efficient communication techniques | |
CN112839038A (en) | Method and system for transmitting data through one-way communication between servers | |
WO2024060408A1 (en) | Network attack detection method and apparatus, device and storage medium | |
US20230239358A1 (en) | Method for fowarding data, device, storage medium and data transmission system | |
CN114679407A (en) | Link aggregation method, device, equipment and storage medium | |
CN106131162B (en) | A method of network service agent is realized based on IOCP mechanism | |
CN114024910A (en) | Extremely-low-delay reliable communication system and method for financial transaction system | |
CN112181681A (en) | Remote calling method and device, computer equipment and storage medium | |
CN113965628A (en) | Message scheduling method, server and storage medium | |
CN115023919A (en) | Firewall rule updating method and device, server and storage medium | |
Hu et al. | Research and implementation of campus information push system based on WebSocket | |
CN108076111B (en) | System and method for distributing data in big data platform | |
CN114928638A (en) | Network behavior analysis method and device and monitoring equipment | |
CN110753043B (en) | Communication method, device, server and medium | |
Ahmad et al. | Protection of centralized SDN control plane from high-rate Packet-In messages | |
CN112988416A (en) | Message processing method, device, equipment and computer readable storage medium | |
Wang et al. | Towards tunable RDMA parameter selection at runtime for datacenter applications |
Legal Events
Date | Code | Title | Description |
---|---|---|---|
PB01 | Publication | ||
PB01 | Publication | ||
SE01 | Entry into force of request for substantive examination | ||
SE01 | Entry into force of request for substantive examination | ||
GR01 | Patent grant | ||
GR01 | Patent grant |