所以,我想学习如何在objective-c中通过tcp套接字来回写入数据,而我似乎无法将其连接到我的服务器。我通过编写c代码来验证我的服务器是否正常运行,以便与服务器连接并且可以正常运行。我无法在objective-c中获得连接。
这是代码 -
- (void)searchForSite
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"URL", PORT, &readStream, &writeStream);
if(!CFWriteStreamOpen(writeStream)) {
NSLog(@"Error, writeStream not open");
return;
}
NSInputStream *inputStream = (__bridge_transfer NSInputStream *)readStream;
NSOutputStream *outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
inStream = inputStream;
outStream = outputStream;
[inputStream open];
[outputStream open];
CFWriteStreamWrite(writeStream, "Hello\n", 6);
}
这个c代码可以工作,并在服务器端给我一个连接:
void con(NSString *x)
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
char *node = "URL";
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(node, PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("client: socket");
continue; }
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("client: connect");
continue;
}
break; }
if (p == NULL) {
fprintf(stderr, "client: failed to connect\n");
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
s, sizeof s);
printf("client: connecting to %s\n", s);
freeaddrinfo(servinfo); // all done with this structure
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1); }
buf[numbytes] = '\0';
printf("client: received '%s'\n",buf);
close(sockfd);
}
URL是ipv4地址。
有什么建议吗?