iOS 真机socket连不上问题

https://cloud.tencent.com/developer/article/1597680

需要先提示权限

#define SOCKET_PORT htons(8040)
#define IP_ADRR "192.168.1.3"

char receive_msg[1024];
char reply_msg[1024];
int connectSocket(){
    int server_socket = socket(AF_INET, SOCK_STREAM, 0);
   // int clientId = socketId;
    if (server_socket == -1) {
            NSLog(@"create socket fail");
            return -1;
    }
    struct sockaddr_in socketAdrr;
    socketAdrr.sin_family = AF_INET;
    socketAdrr.sin_port = SOCKET_PORT;
    /*
    struct in_addr socketIn_adrr;
    
    socketIn_adrr.s_addr = inet_addr(IP_ADRR);
    //char* ip = [str UTF8String];
    //socketIn_adrr.s_addr = inet_addr(ip);
    
    socketAdrr.sin_addr = socketIn_adrr;
     */
    socketAdrr.sin_addr.s_addr = inet_addr(IP_ADRR);
    ///int connect(int sockfd, const struct sockaddr * servaddr, socklen_t addrlen)
    ///参数一:sockfd(socket描述符)
    ///参数二:servaddr(socket地址结构体指针)
    ///参数三:addrlen(socket地址结构体大小)
    int result = connect(server_socket, (const struct sockaddr *)&socketAdrr, sizeof(socketAdrr));
    if(result != 0){
            NSLog(@"客户端:连接失败");
            return -1;
    }else{
        bzero(reply_msg, 1024);
        printf("replay:");
        //scanf("%s", reply_msg);
        strcpy(reply_msg,"hello_1234561111------>");
        if (send(server_socket, reply_msg, 1024, 0) == -1) {
            perror("send error!");
            
            return -1;
        }
        
        bzero(receive_msg, 1024);
        long byte_num = recv(server_socket, receive_msg, 1024, 0);
        receive_msg[byte_num] = '\0';
        printf("server said:%s\n", receive_msg);
        
    }
    close(server_socket);
    return 0;
}
-(void)testHttp
{
    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];//此处修改为自己公司的服务器地址
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            NSLog(@"%@",dict);
        }
    }];
    
    [dataTask resume];
}

- (IBAction)Click:(id)sender {
    [self testHttp];    //self.btn.titleLabel.text = @"hah";
    connectSocket();
}

 

上一篇:Centos 7 安装及配置LDAP


下一篇:super调用父类的构造函数