首先得引入CocoaAsyncSocket這個(gè)類(lèi)庫(kù)英妓,然后建兩個(gè)工程,分別寫(xiě)服務(wù)器端和客戶(hù)端的,客戶(hù)端的IP地址要寫(xiě)自己電腦的哦帖族,端口號(hào)要相同。
服務(wù)器端的demo:
#import"ViewController.h"
#import"GCDAsyncSocket.h"
@interfaceViewController()
@property(weak,nonatomic)IBOutletUITextField*portF;
@property(weak,nonatomic)IBOutletUITextField*messageTF;
@property(weak,nonatomic)IBOutletUITextView*showContentMessageTV;
//服務(wù)器socket(開(kāi)放端口,監(jiān)聽(tīng)客戶(hù)端socket的鏈接)
@property(nonatomic)GCDAsyncSocket*serverSocket;
//保護(hù)客戶(hù)端socket
@property(nonatomic)GCDAsyncSocket*clientSocket;
@end
@implementationViewController
#pragma mark -服務(wù)器socket Delegate
- (void)socket:(GCDAsyncSocket*)sock didAcceptNewSocket:(GCDAsyncSocket*)newSocket{
//保存客戶(hù)端的socket
self.clientSocket= newSocket;
[selfshowMessageWithStr:@"鏈接成功"];
[selfshowMessageWithStr:[NSStringstringWithFormat:@"服務(wù)器地址:%@ -端口:%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];
}
//發(fā)送消息
- (IBAction)sendMessage:(id)sender {
NSData*data = [self.messageTF.textdataUsingEncoding:NSUTF8StringEncoding];
//withTimeout -1:無(wú)窮大爹凹,一直等
//tag:消息標(biāo)記
[self.clientSocketwriteData:datawithTimeout:-1tag:0];
}
//開(kāi)始監(jiān)聽(tīng)
- (IBAction)startReceive:(id)sender {
//2、開(kāi)放哪一個(gè)端口
NSError*error =nil;
BOOLresult = [self.serverSocketacceptOnPort:self.portF.text.integerValueerror:&error];
if(result && error ==nil) {
//開(kāi)放成功
[selfshowMessageWithStr:@"開(kāi)放成功"];
}
}
//接受消息,socket是客戶(hù)端socket镶殷,表示從哪一個(gè)客戶(hù)端讀取消息
- (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禾酱、初始化服務(wù)器socket,在主線程力回調(diào)
self.serverSocket= [[GCDAsyncSocketalloc]initWithDelegate:selfdelegateQueue:dispatch_get_main_queue()];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
客戶(hù)端的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;
//客戶(hù)端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:@"服務(wù)器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];
}
//開(kāi)始連接
- (IBAction)connectAction:(id)sender {
//2绘趋、連接服務(wù)器
[self.clinetSocketconnectToHost:self.addressTF.textonPort:self.portTF.text.integerValuewithTimeout:-1error:nil];
}
//發(fā)送消息
- (IBAction)sendMessageAction:(id)sender {
NSData*data = [self.messageTF.textdataUsingEncoding:NSUTF8StringEncoding];
//withTimeout -1 :無(wú)窮大
//tag:消息標(biāo)記
[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
寫(xiě)完后,分別運(yùn)行兩個(gè)工程陷遮,開(kāi)啟服務(wù)器滓走,textView里會(huì)顯示開(kāi)放成功,然后在客戶(hù)端里連接帽馋,連接成功后搅方,便可以在textfield里打字了,發(fā)送后绽族,服務(wù)器會(huì)收到消息姨涡,同理,服務(wù)器發(fā)送消息吧慢,客戶(hù)端也可以收到涛漂。
流程:
1、先運(yùn)行服務(wù)器检诗,點(diǎn)擊開(kāi)始監(jiān)聽(tīng)匈仗,會(huì)出現(xiàn) “開(kāi)放成功”4個(gè)字底哗。
2、打開(kāi)客戶(hù)端锚沸,填寫(xiě)自己的IP地址跋选,點(diǎn)擊開(kāi)始連接,這時(shí)連接成功會(huì)顯示“鏈接成功”4個(gè)字
3哗蜈、當(dāng)我輸入“111”前标,并點(diǎn)擊發(fā)送,可以在服務(wù)器的textView里收到信息距潘。當(dāng)然反向也可炼列。
如果失敗的話,可以把模擬器之前運(yùn)行的給刪了音比,按照流程重新運(yùn)行一下俭尖。