一.什么是Socket
socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,都可以用“打开open –> 读写write/read –> 关闭close”模式来操作。我的理解就是Socket就是该模式的一个实现,socket即是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO、打开、关闭)。
二.TCPSocket的使用
1.TCP客户端的写法
1).创建客户端套接字对象
_clientSocket = [[AsyncSocket alloc]initWithDelegate:self];
建立与服务器的链接
[_clientSocket connectToHost:@"192.168.1.1" onPort:5555 error:nil];
客户端监听
[_clientSocket readDataWithTimeout:-1 tag:100];
2)客户端代理
建立与服务器的连接
- (BOOL)onSocketWillConnect:(AsyncSocket *)sock
连接服务器成功
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
[sock writeData:[@"登录请求" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:100];
向服务器发送数据成功
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
收到来自服务器的消息
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
断开连接
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
2.TCP服务端的写法
1).创建服务端套接字对象
_serverSocket = [[AsyncSocket alloc]initWithDelegate:self];
if ([_serverSocket acceptOnPort:5555 error:nil])
{
NSLog(@"服务器启动了");
}else
{
NSLog(@"服务器启动失败");
}
2).服务端代理
收到了来自客户端的TCP连接请求
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
[newSocket writeData:[@"蓝翔技校欢迎你..." dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:100];
//保存客户端
_clientSocket = newSocket;
收到了来自客户端的数据
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
服务端发送消息成功
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
//继续监听客户端数据
[_clientSocket readDataWithTimeout:-1 tag:100];
三.UDPSocket的使用
1.创建UDP套接字对象
_recevSocket = [[AsyncUdpSocket alloc]initWithDelegate:self];
_sendSocket = [[AsyncUdpSocket alloc]initWithDelegate:self];
[_recevSocket bindToPort:0x1234 error:nil];
[_sendSocket bindToPort:0x4321 error:nil];
//监听
[_recevSocket receiveWithTimeout:-1 tag:100];
2.UDPSokect代理
收到了对方传过来的消息
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port
发送消息成功
- (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag
3.UDPSoket发送消息
[_sendSocket sendData:[contentField.text dataUsingEncoding:NSUTF8StringEncoding] toHost:ipField.text port:0x1234 withTimeout:-1 tag:200];