In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you an example of TCP connection analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!
1 Overview
Luat connection is simpler than AT, it only needs simple configuration to connect, and it can also deal with data flexibly.
You need to download the luatask script package from the official website or github, or use luatoolsv2 to download script resources automatically. In\ resource\ 8910_script in the tool root directory, the script resources will be updated synchronously with the official website. The specific version may be different from this article, but the features are the same.
The API interface used in the document can be found in the API section of wiki.
There are two sample codes in the demo/socket folder of the script directory. Async is asynchronous socket,sync is synchronous socket.
Synchronization:
The idea of synchronization is that all operations are done before returning to the user. In this way, users wait online for too long, giving users a feeling of stuck (that is, when the system migration is clicked, the interface will not move, but the program is still executing and the feeling of being stuck). In this case, the user cannot close the interface, and if it is closed, the migration program will be interrupted.
Async:
Put the user request into the message queue and feedback to the user, the system migration program has been started, you can close the browser. Then the program slowly writes to the database. This is asynchronism. But the user does not feel stuck and will tell you that your request system has responded. You can close the interface.
Synchronization and asynchronism themselves are relative.
Synchronization is equivalent to when the client sends a request to the server and the client does nothing else while waiting for the server to respond to the request. Return to the client only when the server has finished. In that case, the client needs to wait all the time. Users will be unfriendly to use.
Asynchronism means that when the client sends a request to the server, while waiting for the server to respond, the client can do other things, which saves time and improves efficiency.
There is a reason that asynchrony is good, but some problems need to be solved by synchronization, for example, there are some things we need to get the returned data to operate. These cannot be solved asynchronously.
So please choose according to the actual needs.
2 API description 2.1 Connect to the server
Luat's socket operation is an object-oriented operation, so first use socket.tcp (ssl, cert) to create an object.
Input value type definition bool optional parameter, default is nil,ssl, whether it is ssl connection, true means yes, other means no table optional parameter, default is the certificate configuration required by nil,cert,ssl connection, only if the ssl parameter is true, the parameter is meaningful. The cert format is as follows: {caCert = "ca.crt",-- CA certificate file (Base64 encoded X.509 format), if this parameter exists Indicates that the client will verify the certificate of the server Do not verify clientCert = "client.crt" if it does not exist,-- client certificate file (Base64 encoding X.509 format). This parameter will be used by the server when verifying the client certificate.-- client private key file (Base64 encoding X.509 format) clientPassword = "123456",-- client certificate file password [optional]}
If c = socket.tcp () succeeds, c is the newly created object.
Then use mt:connect (address, port, timeout) to connect to the server
Parameters.
Input value type defines stringaddress server address, supports ip and domain name paramport string or number type, optional parameter of server port number. Default is 120pm timeout optional parameter, connection timeout (in sec)
Return value
Bool result true-successful, false-failed string, id'0'--'8', returns the channel ID number
Mt: represents the object, that is, the c that we created earlier through socket.tcp ()
Use c:connect () to connect to the server.
2.2 receive data 2.2.1 synchronization mode
The synchronous method uses mt:recv (timeout, msg, msgNoResume) to block the operation. When the program runs here, it will wait until the condition is met.
Parameters.
Input value type definition number optional parameter, default is 0 timeout optional parameter, receive timeout, unit millisecond string optional parameter, default is nil,msg optional parameter, control socket thread exit recv blocking state bool optional parameter, default is nil,msgNoResume optional parameter, control socket thread exit recv blocking state, false or nil means "in the recv blocking state, you can exit the blocking state when you receive a msg message" True means not quitting.
Return value
Result data receiving result. True indicates success, false indicates failure data returns the received data if successful; the error is "timeout" when timeout occurs; msg controls the string param of msg when exiting. If it is the false returned by msg, the value of data is the value of msg,param and the parameter of msg.
Take the socket\ sync\ sendInterruptRecv\ testSocket.lua of demo as an example. R is result when the reason for exiting is true when the server sends data, and in other cases, false,s is data. When r is true, data represents the parameter. When r is false, data indicates the reason for exiting blocking. One is timeout, and the other is configured msg. When the value is msg, p represents the parameter carried by msg.
While true do r, s, p = c:recv (120000, "pub_msg") if r then recv_cnt = recv_cnt + # s log.info ("this is the statistics received from the server:", recv_cnt, "and the first 30 bytes:", s:sub (1) 30) elseif s = "pub_msg" then send_cnt = send_cnt + # p log.info ("this is a data message from another thread!", send_cnt, "and the first 30 bytes", p:sub (1) 30) if not c:send (p) then break end elseif s = "timeout" then log.info ("this is the display of waiting for a heartbeat packet to be sent during a timeout!") If not c:send ("ping") then break end else log.info ("this is the display of socket connection error!") Break end end
After the connection to the server is successful, the code enters this endless loop. The first parameter in recv (120000, "pub_msg") indicates the maximum blocking time, which is mainly used for heartbeats to maintain the connection, because timeout exits blocking on the premise that no data is sent or received within this time. The second parameter is the string that controls the exit, which is similar to the principle that sys.subscribe (id, callback) msg is id, which is used to subscribe to data from other protocols. The method of sending data is sys.publish (...). Rev exits and carries parameters when triggered
2.2.2 Asynchronous mode
Asynchronous uses mt:asyncRecv () interface to receive data. Compared with synchronous mode, asynchronous parameters and return value are relatively simple. There is no need to transfer parameters when using, and the return value is the received data directly.
2.3 sending data 2.3.1 synchronization mode
Data can be sent using the mt:send (data) interface, because the synchronization mode is blocked in the receiving part most of the time, so according to the previous instructions for synchronously receiving data, you can configure msg to exit blocking and then send data. You can refer to the demo practice. Configure msg to pub_msg in rev and then use sys.publish to send data to pub_msg through other protocols, and send it directly after exiting the blocking.
-- Test code to send messages to socketsys.taskInit (function () while not socket.isReady () do sys.wait (2000) end sys.wait (10000)-- this is a demonstration of sending data with sys.publish () for I = 1,10 do sys.publish ("pub_msg", string.rep ("0123456789", 1024)) sys.wait (1024) endend 2.3.2 Asynchronous
Asynchronous mode is also relatively simple to send directly using mt:asyncSend (data). One thing to note is that there is no timeout in asynchronous mode, so heartbeat needs to be maintained or configured using mt:asyncSelect (keepAlive, pingreq) to configure heartbeat time and content.
3 luat sample program
The related example programs are located in the demo\ socket folder of the script library, including synchronous, asynchronous and tcp-to-serial port pass-through examples. According to the actual needs, we can choose demo for research.
3.1 turn on and connect to the network
Make the modification based on the demo of the\ script_LuaTask_V2.3.2\ demo\ socket\ sync\ sendInterruptRecv directory. In demo, at the beginning of entering the formal application after boot, a while is used to determine loop blocking. Socket.isReady () indicates whether the network connection is available. If available, it is true, not false.
-- tcp testsys.taskInit (function () local r, s, p local recv_cnt, send_cnt = 0,0 while true do while not socket.isReady () do sys.wait (1000) end c = socket.tcp () while not c:connect (ip, port) do sys.wait (2000) end
In some cases, due to arrears and other reasons, the device socket may be unavailable all the time, so you can add an exception mechanism to restart the device when the socket is unavailable for a long time. The following modifications can be made.
-- timeout for waiting for a network connection local timeout = 90 local-tcp testsys.taskInit (function () local r, s, p local recv_cnt, send_cnt, con_cnt = 0,0,0 while true do while not socket.isReady () do sys.wait (1000) if con_cnt = = timeout then sys.restart ("Network initialization failed!") End con_cnt = con_cnt + 1 end con_cnt = 03.2 Connect to the server
The windows system I use here directly uses the network debugging assistant as server, and if it doesn't have it, it can be tested with http://tcplab.openluat.com/.
Note: no matter whether the server connected to the 2G or 4G module must be a public network, the local area network ip cannot first create a new tcp object through * * socket.tcp (). The subsequent operations are based on this object. Then use c:connect (ip, port) * * to start the connection. If the connection is not successful, the instance program will retry again and again. In the actual project, you can choose how many times the connection fails to enter the flight mode and retry.
C = socket.tcp () while not c:connect (ip, port) do sys.wait (2000) end
After the connection is successful, it enters an endless loop, and the state of the module is judged according to the return condition of rev for business processing.
3.3 socket send and receive messages while true do r, s, p = c:recv (120000, "pub_msg") if r then recv_cnt = recv_cnt + # s log.info ("this is the data statistics received from the server:", recv_cnt, "and the first 30 bytes:", s:sub (1) 30) elseif s = "pub_msg" then send_cnt = send_cnt + # p log.info ("this is a data message from another thread!", send_cnt, "and the first 30 bytes", p:sub (1) 30) if not c:send (p) then break end elseif s = "timeout" then log.info ("this is the display of waiting for a heartbeat packet to be sent during a timeout!") If not c:send ("ping") then break end else log.info ("this is the display of socket connection error!") Break end end
When the first return value r is true, the data comes from the server. When r non-true,s is an internal message, the message first comes from the timeout inside the socket object, and when timeout is set to indicate that there is no message sent or received during the blocking period, then you need to send a heartbeat to keep alive, and the heartbeat packet content can be written according to your own needs. When s is another value, you can send messages from other threads to the socket thread to achieve the purpose of sending data. Demo uses pub_msg. When other threads send messages to pub_msg through the sys.publish interface, the rev of the socket thread will exit the blocking, and then process the message from other threads according to s. In this case, p represents the parameters of the delivered message. Developers can add messages to determine and process different messages, for example, they can actively exit the socket connection based on the message. The interface that sends messages through other threads is shown in the following code
-- Test code to send messages to socketsys.taskInit (function () while not socket.isReady () do sys.wait (2000) end sys.wait (10000)-- this is a demonstration of sending data for I = 1,10 do sys.publish ("pub_msg", string.rep ("0123456789") with sys.publish () 1024) sys.wait (500) end end) 4 related information and purchase links
SOCKETAPI description
Related development board purchase link Air724UG development board Air724 development board use instructions
5 FAQ
Failed to connect to the server
The server must be a public network address
Use the TCP UDP test tool client on PC, or mqtt.fx, to connect to the server to confirm that you can connect successfully and troubleshoot the server
If you connect to the ssl server, confirm whether the core file supports the ssl feature (for example, some core files of the 2G module do not support the ssl feature)
Don't use China Unicom card for 2G module.
Check the module signal, network registration, network attachment, and PDP activation status
Check whether the SIM card is in arrears [4G module has an overdue performance: unable to register for 4G network, can register for 2G network]
A maximum of 8 connections are supported for non-ssl socket at the same time, and the memory of ssl is no more than that.
Troubleshooting of socket anomalies
Search for socket. If socket:connect: core sock conn error or socket:connect: connect fail appears, the socket connection failed
Search for socket. If send fail appears, it means the delivery failed.
Search for socket. If socket.rtos.MSG_SOCK_CLOSE_IND appears, socket' is passively disabled.
The above is all the contents of the article "sample Analysis of TCP connections". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.