首先得引入CocoaAsyncSocket这个类库,然后建两个工程,分别写服务器端和客户端的,客户端的IP地址要写自己电脑的哦,端口号要相同。
服务器端的demo:
#import"ViewController.h"
#import"GCDAsyncSocket.h"
@interfaceViewController()
@property(weak,nonatomic)IBOutletUITextField*portF;
@property(weak,nonatomic)IBOutletUITextField*messageTF;
@property(weak,nonatomic)IBOutletUITextView*showContentMessageTV;
//服务器socket(开放端口,监听客户端socket的链接)
@property(nonatomic)GCDAsyncSocket*serverSocket;
//保护客户端socket
@property(nonatomic)GCDAsyncSocket*clientSocket;
@end
@implementationViewController
#pragma mark -服务器socket Delegate
- (void)socket:(GCDAsyncSocket*)sock didAcceptNewSocket:(GCDAsyncSocket*)newSocket{
//保存客户端的socket
self.clientSocket= newSocket;
[selfshowMessageWithStr:@"链接成功"];
[selfshowMessageWithStr:[NSStringstringWithFormat:@"服务器地址:%@ -端口:%d", newSocket.connectedHost, newSocket.connectedPort]];
[self.clientSocketreadDataWithTimeout:-1tag:0];
}
//收到消息
- (void)socket:(GCDAsyncSocket*)sock didReadData:(NSData*)data withTag:(long)tag{
NSString*text = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
[selfshowMessageWithStr:text];
[self.clientSocketreadDataWithTimeout:-1tag:0];
}
//发送消息
- (IBAction)sendMessage:(id)sender {
NSData*data = [self.messageTF.textdataUsingEncoding:NSUTF8StringEncoding];
//withTimeout -1:无穷大,一直等
//tag:消息标记
[self.clientSocketwriteData:datawithTimeout:-1tag:0];
}
//开始监听
- (IBAction)startReceive:(id)sender {
//2、开放哪一个端口
NSError*error =nil;
BOOLresult = [self.serverSocketacceptOnPort:self.portF.text.integerValueerror:&error];
if(result && error ==nil) {
//开放成功
[selfshowMessageWithStr:@"开放成功"];
}
}
//接受消息,socket是客户端socket,表示从哪一个客户端读取消息
- (IBAction)ReceiveMessage:(id)sender {
[self.clientSocketreadDataWithTimeout:11tag:0];
}
- (void)showMessageWithStr:(NSString*)str{
self.showContentMessageTV.text= [self.showContentMessageTV.textstringByAppendingFormat:@"%@\n",str];
}
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 1、初始化服务器socket,在主线程力回调
self.serverSocket= [[GCDAsyncSocketalloc]initWithDelegate:selfdelegateQueue:dispatch_get_main_queue()];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
客户端的demo:
#import"ViewController.h"
#import"GCDAsyncSocket.h"
@interfaceViewController()
@property(weak,nonatomic)IBOutletUITextField*addressTF;
@property(weak,nonatomic)IBOutletUITextField*portTF;
@property(weak,nonatomic)IBOutletUITextField*messageTF;
@property(weak,nonatomic)IBOutletUITextView*showMessageTF;
//客户端socket
@property(nonatomic)GCDAsyncSocket*clinetSocket;
@end
@implementationViewController
#pragma mark - GCDAsynSocket Delegate
- (void)socket:(GCDAsyncSocket*)sock didConnectToHost:(NSString*)host port:(uint16_t)port{
[selfshowMessageWithStr:@"链接成功"];
[selfshowMessageWithStr:[NSStringstringWithFormat:@"服务器IP:%@", host]];
[self.clinetSocketreadDataWithTimeout:-1tag:0];
}
//收到消息
- (void)socket:(GCDAsyncSocket*)sock didReadData:(NSData*)data withTag:(long)tag{
NSString*text = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
[selfshowMessageWithStr:text];
[self.clinetSocketreadDataWithTimeout:-1tag:0];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{
[self.viewendEditing:YES];
}
//开始连接
- (IBAction)connectAction:(id)sender {
//2、连接服务器
[self.clinetSocketconnectToHost:self.addressTF.textonPort:self.portTF.text.integerValuewithTimeout:-1error:nil];
}
//发送消息
- (IBAction)sendMessageAction:(id)sender {
NSData*data = [self.messageTF.textdataUsingEncoding:NSUTF8StringEncoding];
//withTimeout -1 :无穷大
//tag:消息标记
[self.clinetSocketwriteData:datawithTimeout:-1tag:0];
}
//接收消息
- (IBAction)receiveMessageAction:(id)sender {
[self.clinetSocketreadDataWithTimeout:11tag:0];
}
- (void)showMessageWithStr:(NSString*)str{
self.showMessageTF.text= [self.showMessageTF.textstringByAppendingFormat:@"%@\n", str];
}
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//1、初始化
self.clinetSocket= [[GCDAsyncSocketalloc]initWithDelegate:selfdelegateQueue:dispatch_get_main_queue()];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
写完后,分别运行两个工程,开启服务器,textView里会显示开放成功,然后在客户端里连接,连接成功后,便可以在textfield里打字了,发送后,服务器会收到消息,同理,服务器发送消息,客户端也可以收到。
流程:
1、先运行服务器,点击开始监听,会出现 “开放成功”4个字。
2、打开客户端,填写自己的IP地址,点击开始连接,这时连接成功会显示“链接成功”4个字
3、当我输入“111”,并点击发送,可以在服务器的textView里收到信息。当然反向也可。
如果失败的话,可以把模拟器之前运行的给删了,按照流程重新运行一下。