iOS 简单socket连接

时间:2023-03-08 20:07:53

- (void)CreateSocket{

NSString *host = [self.realStreamDict objectForKey:@"StreamSeverIP"];

NSString * StreamServerPort = [self.realStreamDict objectForKey:@"StreamSeverPort"];

//    NSString *host = @"172.16.24.223";

//

//    NSString * StreamServerPort =@"6123";

if(host.length==0||_isConnectToSocketServer||_haveConnectSocket){

return;

}

_haveConnectSocket = YES;

BOOL socketConnectSuccess =  [self connection:host port:StreamServerPort.intValue];

if (socketConnectSuccess ) {

NSLog(@"sock连接成功");

}

else{

[self CreateSocket];

return;

NSLog(@"sock连接失败");

}

//选择性发送头校验

NSData * headData = [self sendHeaderInformation];

if (headData.length>0) {

send(self.clientSocket,headData.bytes,headData.length, 0);

}

uint8_t buffer[1024];

//    从服务器接收过来的数据

ssize_t recvLen = recv(self.clientSocket, buffer, sizeof(buffer), 0);

// 按照服务器返回的长度,从 buffer 中,读取二进制数据,建立 NSData 对象

if(recvLen>0){

NSData *data = [NSData dataWithBytes:buffer length:recvLen];

NSString *info = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

if ([info hasPrefix:@"TXEH"]) {

self.isConnectToSocketServer = YES;

NSLog(@"连接socket 成功。。。");

}

else{

close(self.clientSocket);

[self CreateSocket];

}

}

}

// MARK: Socket

- (BOOL)connection:(NSString *)hostText port:(int)port {

// socket

/**

参数

domain:    协议域,AF_INET(IPV4的网络开发)

type:      Socket 类型,SOCK_STREAM(TCP)/SOCK_DGRAM(UDP,报文)

protocol:  IPPROTO_TCP,协议,如果输入0,可以根据第二个参数,自动选择协议

返回值

socket,如果 > 0 就表示成功

*/

self.clientSocket = socket(AF_INET, SOCK_STREAM, 0);

if (self.clientSocket > 0) {

NSLog(@"Socket Create success %d", self.clientSocket);

} else {

NSLog(@"Socket Create error");

}

//connection 连接到“服务器”

/**

参数

1> 客户端socket

2> 指向数据结构sockaddr的指针,其中包括目的端口和IP地址

服务器的"结构体"地址,C语言没有对象

3> 结构体数据长度

返回值

0 成功/其他 错误代号,非0即真

*/

struct sockaddr_in serverAddress;

// IPV4 - 协议

serverAddress.sin_family = AF_INET;

// inet_addr函数可以把ip地址转换成一个整数

serverAddress.sin_addr.s_addr = inet_addr(hostText.UTF8String);

// 端口小端存储

serverAddress.sin_port = htons(port);

int result = connect(self.clientSocket, (const struct sockaddr *)&serverAddress, sizeof(serverAddress));

int nNetTimeout=1000;//1秒

setsockopt(self.clientSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nNetTimeout, sizeof(int));

// 如果连接成功返回 YES 33

return (result == 0);

}