Reproduced from: http://www.cocoachina.com/bbs/read.php? Tid = 21242 & page = 1
Connect iPhone wifi to the Internet using Socket
1. Use asyncsocket (http://code.google.com/p/cocoaasyncsocket)
As a base library of socket.
2. An echoserver is provided in this library. We can use this program to run a test server directly on the Mac system.
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 on 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) ***** ocket :( asyncsocket *) sock didconnecttohost :( nsstring *) host port :( uint16) port;
B:-(void) ***** ocketdidsecure :( asyncsocket *) sock;
C:-(void) ***** ocket :( asyncsocket *) sock willdisconnectwitherror :( nserror *) err;
D:-(void) ***** ocketdiddisconnect :( asyncsocket *) sock;
E:-(void) ***** ocket :( 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.