Persistent connection of AsyncSocket and asyncsocket
Background: instant communication must be established with servers for a long time, and real-time connections must be established with smart hardware to synchronize the status of smart hardware, recently, when I was working on a project, I encountered the need to update the status of the smart hardware in real time (such as the power of the smart hardware and other working states), and communicated with the smart hardware through the server, therefore, you need to establish a connection with the server in real time. The specific implementation is as follows:
Procedure:
1. Import the AsyncSocket. m/AsyncSocket. h file to the xcode project.
2. Add the CFNetwork. framework.
3. import the # import "AsyncSocket. h" header file.
4. Create an AsyncSocket object, periodically send a heartbeat packet timer object, and a heartbeat packet data content object.
5. Start to connect to the server. The connection requires the server address and port number.
6. Create a timer for sending heartbeat packets
LongPollTime indicates the gap between the sending time of the heartbeat packet.
7. Send the heartbeat packet content. Here I am sending an empty byte.
8. Send heartbeat packets and stop heartbeat packets
9. asyncSocket proxy
// Connect soon
-(BOOL) onSocketWillConnect :( AsyncSocket *) sock
// Connection completed
-(Void) onSocket :( AsyncSocket *) sock didConnectToHost :( NSString *) host port :( UInt16) port
// The message has been sent.
-(Void) onSocket :( AsyncSocket *) sock didWriteDataWithTag :( long) tag
// Receives the message
-(Void) onSocket :( AsyncSocket *) sock didReadData :( NSData *) data withTag :( long) tag
Program Source Address http://pan.baidu.com/s/1buwHC6