AsyncSocket是一个用Object-c封装好的网络通讯API,调用方便,容易实现
使用AsyncSocket可以很方便的与其它系统进行Socket通信, AsyncSocket包括TCP和UDP,通过实现委托AsyncSocketDelegate进行交互。
下面是TCP通讯
API 下载地址 :点击下载
首先,调用此API时需先引入CFNetWork.framework
然后在#import "AsyncSocket.h"就可以直接调用了
闲话不多说,上代码:
SocketServer端代码:
.h文件
- @interface ViewController :UIViewController<AsyncSocketDelegate,UITextFieldDelegate>
- {
- AsyncSocket *listener;
-
- NSMutableArray *connectionSockets;
-
- IBOutlet UITextView *ReceiveData;
- IBOutlet UITextField *message;
- }
-
- @property (nonatomic, retain)AsyncSocket *listener;
- @property (nonatomic, retain)UITextField *message;
- @property (nonatomic, retain)UITextView *ReceiveData;
-
-
- - (IBAction)sendMessage:(id)sender;
- - (IBAction)textEndEditting:(id)sender;
.m文件
客户端代码:
h文件
- #import <UIKit/UIKit.h>
- #import "AsyncSocket.h"
-
- @interface ViewController :UIViewController<UITextFieldDelegate>
- {
- AsyncSocket *socket;
- }
- @property (retain, nonatomic) IBOutlet UITextField *clientIPAddress;
- @property (retain, nonatomic) IBOutlet UITextView *ReceiveData;
- @property (retain, nonatomic) IBOutlet UITextField *SendMessage;
- @property (retain, nonatomic) IBOutlet UILabel *Status;
-
- - (IBAction)Send:(id)sender;
- - (IBAction)ConnectToSever:(id)sender;
- @end
m文件
- #import "ViewController.h"
- #import "Config.h"
- @interface ViewController ()
-
- @end
-
- @implementation ViewController
-
- - (void)viewDidLoad
- {
- _clientIPAddress.delegate=self;
- [_clientIPAddress setTag:1];
- _SendMessage.delegate=self;
- [_SendMessage setTag:2];
- _ReceiveData.editable=NO;
- [superviewDidLoad];
-
- }
- - (void) textFieldDidBeginEditing:(UITextField *)textField
- {
- if([textField tag]==2)
- {
- [self viewUp];
- }
- }
- - (BOOL)textFieldShouldReturn:(UITextField *)textField;
- {
-
- [textField resignFirstResponder];
- if([textField tag]==2)
- {
- [self viewDown];
- }
- return YES;
- }
- - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
- {
- returnUIInterfaceOrientationPortrait;
- }
- - (void)didReceiveMemoryWarning
- {
- [superdidReceiveMemoryWarning];
-
- }
- - (IBAction)Send:(id)sender {
- if(![_SendMessage.textisEqualToString:@""] && ![_clientIPAddress.textisEqualToString:@""])
- {
- NSString *message=[NSStringstringWithFormat:@"%@:%@",_clientIPAddress.text,_SendMessage.text];
- if(socket==nil)
- {
- socket=[[AsyncSocketalloc]initWithDelegate:self];
- }
-
- [socket writeData:[messagedataUsingEncoding:NSUTF8StringEncoding]withTimeout:-1tag:0];
- _ReceiveData.text=[NSStringstringWithFormat:@"me:%@",_SendMessage.text];
- }
- else
- {
- UIAlertView *alert=[[UIAlertViewalloc]initWithTitle:@"Waring"message:@"Please input Message!"delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil,nil];
- [alert show];
- [alert release];
- }
- }
-
- - (IBAction)ConnectToSever:(id)sender {
- if(socket==nil)
- {
- socket=[[AsyncSocketalloc]initWithDelegate:self];
- NSError *error=nil;
- if(![socketconnectToHost:_IP_ADDRESS_V4_onPort:_SERVER_PORT_error:&error])
- {
- _Status.text=@"连接服务器失败!";
- }
- else
- {
- _Status.text=@"已连接!";
- }
- }
- else
- {
- _Status.text=@"已连接!";
- }
- }
-
- #pragma AsyncScoket Delagate
- - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
- NSLog(@"onSocket:%p didConnectToHost:%@ port:%hu",sock,host,port);
- [sock readDataWithTimeout:1tag:0];
- }
- - (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
- {
- [sock readDataWithTimeout: -1tag: 0];
- }
-
- - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
- NSString* aStr = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
- self.ReceiveData.text = aStr;
- [aStr release];
- [socket readDataWithTimeout:-1tag:0];
- }
-
- - (void)onSocket:(AsyncSocket *)sock didSecure:(BOOL)flag
- {
- NSLog(@"onSocket:%p didSecure:YES", sock);
- }
-
- - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
- {
- NSLog(@"onSocket:%p willDisconnectWithError:%@", sock, err);
- }
-
- - (void)onSocketDidDisconnect:(AsyncSocket *)sock
- {
-
- NSLog(@"onSocketDidDisconnect:%p", sock);
- NSString *msg =@"Sorry this connect is failure";
- _Status.text=msg;
- [msg release];
- socket = nil;
- }
- - (void) viewUp
- {
- CGRect frame=self.view.frame;
- frame.origin.y=frame.origin.y-215;
- [UIView beginAnimations:nilcontext:nil];
- [UIView setAnimationDuration:0.3f];
- [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
- self.view.frame=frame;
- [UIView commitAnimations];
- }
- - (void) viewDown
- {
- CGRect frame=self.view.frame;
- frame.origin.y=frame.origin.y+215;
- [UIView beginAnimations:nilcontext:nil];
- [UIView setAnimationDuration:0.3f];
- [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
- self.view.frame=frame;
- [UIView commitAnimations];
- }
- #pragma end Delegate
- - (void)dealloc {
- [_ReceiveData release];
- [_SendMessage release];
- [_Status release];
- [_clientIPAddress release];
- [super dealloc];
- }
Demo下载地址:客户端下载 服务端下载