iOS中Socket编程有实现方式有:
一、使用系统自带CFsocket
导入头文件:
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <unistd.h>
二、利用第三方框架CocoaAsynSocket
1、利用CocoaAsynSocket实现Socket服务端
#import "ViewController.h"
#import "GCDAsyncSocket/GCDAsyncSocket.h"
@interface ViewController () <GCDAsyncSocketDelegate>
@property(nonatomic,strong) GCDAsyncSocket *serverSocket;
@property(nonatomic,strong) NSMutableArray *clientSocketArray; //保存客服端的所有Socket
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self start];
// [[NSRunLoop currentRunLoop] run]; 调用运行循环 保证线程一直开启
}
-(NSMutableArray *)clientSocketArray
{
if (!_clientSocketArray) {
_clientSocketArray = [NSMutableArray array];
}
return _clientSocketArray;
}
//开启服务端监听
-(void)start
{
GCDAsyncSocket *serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
NSError *error = nil;
[serverSocket acceptOnPort:8888 error:&error];
if (!error) {
NSLog(@"服务端已经开启");
} else {
NSLog(@"服务端开启失败");
}
self.serverSocket = serverSocket; //需要对服务端Socket进行强引用,否则创建完就销毁了
}
#pragma mark - 有客户端链接
//sock为服务端socket,newSocket为客户端socket
-(void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
NSLog(@"有客服端连接服务器%@----%@",sock,newSocket);
[self.clientSocketArray addObject:newSocket]; //需要将客户端的socket保存到数组,这样才能保证newSocket持续存在
//当客户端一连接成功就发送数据给它
NSMutableString *serverceStr = [NSMutableString string];
[serverceStr appendString:@"欢迎来到10086在线服务,请输入下面数组"];
[serverceStr appendString:@"[0]在线充值"];
[serverceStr appendString:@"[4]退出"];
// 向调用方法的socket写入数据即是这里是向客户端socket发送数据
[newSocket writeData:[serverceStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
//监听客户端发送数据
[newSocket readDataWithTimeout:-1 tag:0];
}
#pragma mark - 读取客户端请求的数据
//当一个socket已经把数据读入内存中时被调用。如果发生错误则不被调用
-(void)socket:(GCDAsyncSocket *)clientSocket didReadData:(NSData *)data withTag:(long)tag
{
//将客户端输入的数据转化为整数 根据数字回复不同的内容
NSString *tempStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSUInteger num = [tempStr integerValue];
NSString *reseponseStr = nil;
switch (num) {
case 1:
reseponseStr = @"充值话费忙\n";
break;
case 4:
reseponseStr = @"恭喜你成功退出\n";
break;
default:
break;
}
//处理请求返回数据给客户端
[clientSocket writeData:[reseponseStr dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
if (num == 4) { //当用户输入数字4时 即断开链接只要将客户端的socket从clientSocketArray中删除即可
[self.clientSocketArray removeObject:clientSocket];
}
#warning mark - 每次读完数据后都要调用一次监听数据的方法
[clientSocket readDataWithTimeout:-1 tag:0];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
2、利用CocoaAsynSocket实现Socket客户端(未完,待续)