CAsysncSocket-tcp tool-AsyncSocket usage.

Source: Internet
Author: User

========================================================== ================================
The programming of the AsyncSocket network library under the iPhone is described in this article. The CFNetwork C library programming is recommended for the iphone standard, but programming is quite annoying. In other operating systems, classes are often used to encapsulate Socket functions. For example, the CAsysncSocket of MFC also has a similar open-source project on the iphone. cocoa AsyncSocket Library


Http://code.google.com/p/cocoaasyncsocket/

Here we only use the example above. You can use it in your project. If you have any questions, please leave a message to discuss it.

----------------

Note that CAsysncSocket has asynchronous processing of tcp and udp connections, so you only need to call them in the main thread.

 


Import AsyncSocket. h AsyncSocket. m to your project,

In your own util, add the code

[Cpp]
01. # pragma mark tcp
02.-(void) connectToHost :( NSString *) host port :( int) port {
03. socket = [[AsyncSocket alloc] initWithDelegate: self]; // set the callback delegate
04. // TODO: disconnect from the LAN.
05. [socket disconnect]; // disconnect the tcp Connection
06. // socket
07. NSLog (@ "tcp connecting to host: % @, port: % d", host, port );
08. @ try {
09. [socket connectToHost: host onPort: port error: nil];
10. [socket readDataWithTimeout:-1 tag: 1]; // This only times out. If the timeout value is negative, it never times out.
11 .}
12. @ catch (NSException * exception) {// exception Handling
13. NSLog (@ "connect exception % @, % @", [exception name], [exception description]);
14 .}
15 .}
16. // corresponding callback function
17.-(void) onSocket :( AsyncSocket *) sock didConnectToHost :( NSString *) host port :( UInt16) port {
18. NSLog (@ "did connect to host % @: % d", host, port );
19 .}
20.-(void) sendMessage :( NSString *) msg {
21. NSLog (@ "tcp send msg: % @", msg );
22. [socket readDataWithTimeout: SOCKET_TIMEOUT tag: 1];
23. [socket writeData: [msg dataUsingEncoding: NSUTF8StringEncoding] withTimeout: SOCKET_TIMEOUT tag: 1];
24 .}
25.-(void) onSocket :( AsyncSocket *) sock didReadData :( NSData *) data withTag :( long) tag {
26. NSString * message = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] autorelease];
27. NSLog (@ "% f receive ReadData is: % @", [[NSDate date] timeIntervalSince1970], message );
28.
29 .}
30.-(NSTimeInterval) onSocket :( AsyncSocket *) sock shouldTimeoutReadWithTag :( long) tag elapsed :( NSTimeInterval) elapsed bytesDone :( NSUInteger) length {
31. NSLog (@ "onSocket: shouldTimeout-ReadWithTag :-----------");
32. return 0;
33 .}
34.-(NSTimeInterval) onSocket :( AsyncSocket *) sock shouldTimeoutWriteWithTag :( long) tag elapsed :( NSTimeInterval) elapsed bytesDone :( NSUInteger) length {
35. NSLog (@ "onSocket: shouldTimeout-WriteWithTag :-----------");
36. return 0;
37 .}
38.
39.-(void) onSocket :( AsyncSocket *) sock didWriteDataWithTag :( long) tag {
40. NSLog (@ "didWriteDataWithTag tag: % ld", tag );
41 .}
42.-(void) onSocketDidDisconnect :( AsyncSocket *) sock {
43. NSLog (@ "onSocketDidDisconnect sock: % @", sock );
44. [viewController onLocalDisconnect: 0];
45.
46 .}
# Pragma mark tcp
-(Void) connectToHost :( NSString *) host port :( int) port {
Socket = [[AsyncSocket alloc] initWithDelegate: self]; // set the callback delegate
// TODO must be disconnected from the LAN.
[Socket disconnect]; // disconnect the tcp Connection
// Socket
NSLog (@ "tcp ing to host: % @, port: % d", host, port );
@ Try {
[Socket connectToHost: host onPort: port error: nil];
[Socket readDataWithTimeout:-1 tag: 1]; // This only times out. If the timeout value is negative, it never times out.
}
@ Catch (NSException * exception) {// exception Handling
NSLog (@ "connect exception % @, % @", [exception name], [exception description]);
}
}
// Corresponding callback function
-(Void) onSocket :( AsyncSocket *) sock didConnectToHost :( NSString *) host port :( UInt16) port {
NSLog (@ "did connect to host % @: % d", host, port );
}
-(Void) sendMessage :( NSString *) msg {
NSLog (@ "tcp send msg: % @", msg );
[Socket readDataWithTimeout: SOCKET_TIMEOUT tag: 1];
[Socket writeData: [msg dataUsingEncoding: NSUTF8StringEncoding] withTimeout: SOCKET_TIMEOUT tag: 1];
}
-(Void) onSocket :( AsyncSocket *) sock didReadData :( NSData *) data withTag :( long) tag {
NSString * message = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] autorelease];
NSLog (@ "% f receive ReadData is: % @", [[NSDate date] timeIntervalSince1970], message );

}
-(NSTimeInterval) onSocket :( AsyncSocket *) sock shouldTimeoutReadWithTag :( long) tag elapsed :( NSTimeInterval) elapsed bytesDone :( NSUInteger) length {
NSLog (@ "onSocket: shouldTimeout-ReadWithTag :-----------");
Return 0;
}
-(NSTimeInterval) onSocket :( AsyncSocket *) sock shouldTimeoutWriteWithTag :( long) tag elapsed :( NSTimeInterval) elapsed bytesDone :( NSUInteger) length {
NSLog (@ "onSocket: shouldTimeout-WriteWithTag :-----------");
Return 0;
}

-(Void) onSocket :( AsyncSocket *) sock didWriteDataWithTag :( long) tag {
NSLog (@ "didWriteDataWithTag tag: % ld", tag );
}
-(Void) onSocketDidDisconnect :( AsyncSocket *) sock {
NSLog (@ "onSocketDidDisconnect sock: % @", sock );
[ViewController onLocalDisconnect: 0];

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.