Preface
Continuing from the previous article, Building a Lightweight RunLoop, Part 1, let’s keep analyzing.
LWURLConnection
LWURLConnection is one of the more interesting parts of
this framework, and also one of the more complex ones. After reading it,
it should help a lot with understanding AFNetworking. Here is the code
directly:
1 | - (void)performURLConnectionOnRunLoopThread |
LWURLConnection Initialization
1 | - (instancetype _Nonnull)initWithRequest:(NSMutableURLRequest * _Nullable)request |
LWURLConnection holds a
LWConnectionInternal internally and sets itself as the
delegate of LWConnectionInternal.
LWConnectionInternal Initialization
1 | - (instancetype)init |
1 | - (void)start |
The start method starts a child thread and executes
startInternal. Inside that method, it establishes the
connection, prepares request parameters, and creates the HTTP request.
Let’s break it down step by step.
Establishing the Socket Connection
1 | - (BOOL)establishConnection |
1 | bool LWConnHelper::establishSocket(const char *ip, const int port) |
Preparing Request Headers and Body
This part is responsible for request-parameter setup.
1 | - (void)prepareHttpRequest |
1 | - (void)prepareHTTPBody |
1 | void LWConnHelper::sendMsg(const char *content, int length) |
Creating the HTTP Request
1 | void LWConnHelper::createHttpRequest(int timeoutMills) |
Actually, the name createHttpRequest is not quite
accurate. Inside this method, it is already waiting for network data
through IO multiplexing with select. The request itself has
already been sent in prepareHttpRequest.
Network Callback Flow
1 | @class LWConnectionInternal; |
LWConnectionInternal has a
LWConnectionInternalDelegate internally, and it delegates
the network result to LWURLConnection.
1 | - (void)internal_connectionDidFinishLoading:(LWConnectionInternal * _Nonnull)connection |
Using internal_connectionDidFinishLoading as an example,
it wraps the delegate method of LWURLConnection, which is
the outer business layer, into an LWMessage, then calls the
familiar [_runloop postMessage:msg], sending it into the
RunLoop message queue.
So LWURLConnection itself performs network requests
based on socket and select. Once the network result comes
back, it interacts with the RunLoop again: the delegate method is
wrapped as a message and added to the RunLoop message queue. What
happens next is handled by the RunLoop itself.
LWPort
The most basic concept in Mach is the message. Messages are passed between two ports. By design, any two ports can pass messages to each other, whether they are on the same machine or on a remote host. The source code discussed here uses ports on the same machine.
Sending a message from one port to another is essentially placing the message into a queue until the receiver can process it.
For example, CFRunLoop has two kinds of
CFRunLoopSource:
source0: handles events such asUIEventandCFSocket.source1: Mach-port-driven, such asCFMachPortandCFMessagePort.
From the name alone, source1 is clearly related to
ports.
Leader
First create a thread, obtain the corresponding runloop, define a
LWSocketPort object named _leaderPort, set its
port to 8082, and add _leaderPort to the
runloop.
1 | @autoreleasepool |
1 | - (void)addPort:(LWPort *)aPort forMode:(NSString *)mode |
Follower
At the same time, another thread is created with
detachNewThreadSelector, and a WorkerClass
object is defined.
1 | _worker = [[WorkerClass alloc] init]; |
When the follower port is added, the runloop registers it as a socket-client file descriptor:
1 | - (void)addPort:(LWPort *)aPort forMode:(NSString *)mode |
LWSocket
Now look at the initialization of LWSocket:
1 | - (BOOL)initInternalWithTCPPort:(unsigned short)port |
- For the leader, the main job is to define a socket, open a network communication port, bind a fixed network address such as
127.0.0.1and port8082, then calllistento listen for requests.- For the follower, the main job is to define a socket with an automatically assigned port, then call
connectto connect to the server.connectandbindhave similar parameter forms. The difference is thatbindreceives the local address, whileconnectreceives the peer address.- This is very typical socket programming.
Message Sending
At this point, both FollowPort and
LeaderPort have their own threads and corresponding
runloops.
Take the follower sending a message to the leader as an example.
First package the message as LWPortMessage, then call
sendBeforeDate, which enters
internalSendBeforDate.
1 | - (void)actualSendContent:(id)content |
In internalSendBeforDate, it first obtains the
destination port, then calls the runloop’s send method:
1 | - (void)send:(NSData *)data toFd:(int)fd |
Message Receiving
In the leader’s runloop, kevent detects a change on the
socket file descriptor and wakes up the thread. It then calls
handleFollowerToLeader, reads out the message sent earlier,
and one complete message send/receive flow ends.
1 | - (BOOL)handleFollowerToLeader:(int)event fd:(int)fd |
Summary
After analyzing this source code, go back and think carefully about RunLoop again. If possible, dig deeper. If this article can improve your understanding even a little compared with before, then it has served its purpose.
Finally, I will borrow another diagram from the author’s GitHub. Thanks again to wuyunfeng.