IPhoneWifi usageSocketConnecting to the Internet is the content to be introduced in this article.ServerThe process of sending and receiving messages. Let's just look at the details.
1. Use AsyncSocket (http://code.google.com/p/cocoaasyncsocket/)Socket.
2. An EchoServer is provided in this database. We can use this program to run a test on the MAC system.ServerUp.
3. Add AsyncSocket to the iPhone project according to the WIKI of AsyncSocket (http://code.google.com/p/cocoaasyncsocket/wiki/iPhone). Remember to define the TARGET_ OS _IPHONE macro in the project.
4. The compilation project passes.
5. Connection server code:
- // Create a Socket entity and connect to port 7777 of the local server
- _ Client = [[AsyncSocket alloc] initWithDelegate: self];
- NSError * err = nil;
- If (! [_ Client connectToHost: @ "127.0.0.1" onPort: 7777 withTimeout: 1.0f error: & err]) {
- NSLog (@ "client net: % @", err );
- }
-
- // Add the Event Response Function
- A:-(void) onSocket :( AsyncSocket *) sock didConnectToHost :( NSString *) host port :( UInt16) port;
- B:-(void) onSocketDidSecure :( AsyncSocket *) sock;
- C:-(void) onSocket :( AsyncSocket *) sock willDisconnectWithError :( NSError *) err;
- D:-(void) onSocketDidDisconnect :( AsyncSocket *) sock;
- E:-(void) onSocket :( AsyncSocket *) sock didReadData :( NSData *) data withTag :( long) tag;
-
- // Request to read data in function A. The AsyncSocket calls function E when receiving data.
- [_ Client readDataWithTimeout:-1 tag: 0];
-
- // After function E is called, The Read Request ends. We don't want it to end, so we add it at the end of function E so that the read process can continue.
- [_ Client readDataWithTimeout:-1 tag: 0];
-
- // Record the input sock in function A. This is the socket interface of the server we connect.
- _ Server = sock;
-
- // Send data to the server
- NSData * data;
- [_ Server writeData: data withTimeout:-1 tag: 1];
6. In this way, we can basically implement the process of sending and receiving messages with the server (Note: These callback functions are implemented in the main thread and are not in other threads)
7. You have not paid too much attention to other response events.
Summary: DetailsIPhone WifiUseSocketConnectionInternetI hope this article will help you!