网络通信,有一个CocoaAsyncSocket这个类库,然后建两个工程,分别写服务器端和客户端的,客户端的IP地址要写自己电脑的,端口号要相同。
可以GCD 或者RunLoop 我用的是GCD的,直接上代码,有注释,都能看懂
- 服务器.m里的
- -
import “ViewController.h”
import “GCDAsyncSocket.h”
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *portF;
@property (weak, nonatomic) IBOutlet UITextField *messageTF;
@property (weak, nonatomic) IBOutlet UITextView *showContentMessageTV;
//服务器socket(开放端口,监听客户端socket的链接)
@property (nonatomic) GCDAsyncSocket *serverSocket;
//保护客户端socket
@property (nonatomic) GCDAsyncSocket *clientSocket;
@end
@implementation ViewController
pragma mark - 服务器socket Delegate
- (void)socket:(GCDAsyncSocket )sock didAcceptNewSocket:(GCDAsyncSocket )newSocket{
//保存客户端的socket
self.clientSocket = newSocket;
[self showMessageWithStr:@”链接成功”];
[self showMessageWithStr:[NSString stringWithFormat:@”服务器地址:%@ -端口: %d”, newSocket.connectedHost, newSocket.connectedPort]];
[self.clientSocket readDataWithTimeout:-1 tag:0];
}
//收到消息
- (void)socket:(GCDAsyncSocket )sock