iPhone socket 编程之BSD Socket篇
最后為了造福大家,筆者附上完整 的代碼,頭文件如下:
?
//
//??BSDHttpExampleViewController.h
//??BSDHttpExample
//
//??Created by sun dfsun2009 on 09-11-12.
//??Copyright __MyCompanyName__ 2009. All rights reserved.
//
?
#import <UIKit/UIKit.h>
?
#define MYPORT 4880
#import <stdio.h>
#import <stdlib.h>
#import <unistd.h>
#import <arpa/inet.h>
#import <sys/types.h>
#import <sys/socket.h>
#import <netdb.h>
?
@interface BSDHttpExampleViewController : UIViewController {
????int sockfd;
????struct sockaddr_in their_addr;
}
?
@end
?
實現(xiàn)文件如下:
?
//
//??BSDHttpExampleViewController.m
//??BSDHttpExample
//
//??Created by sun dfsun2009 on 09-11-12.
//??Copyright __MyCompanyName__ 2009. All rights reserved.
//
?
#import "BSDHttpExampleViewController.h"
?
@implementation BSDHttpExampleViewController
?
#define HTTPMETHOD @"GET"
#define HTTPVERSION @"HTTP/1.1"
#define HTTPHOST @"Host"
?
#define KENTER @"\r\n"
#define KBLANK @" "
?
/*
?// The designated initializer. Override to perform setup that is required before the view is loaded.
?- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
?if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
?// Custom initialization
?}
?return self;
?}
?*/
?
/*
?// Implement loadView to create a view hierarchy programmatically, without using a nib.
?- (void)loadView {
?}
?*/
?
void error_handle(char *errorMsg)
{
????fputs(errorMsg, stderr);
????fputc('\n',stderr);
????exit(1);
}
?
- (NSMutableString*) makeHttpHeader:(NSString*) hostName
{
????NSMutableString *header = [[NSMutableString alloc] init];
???
????[header appendFormat:HTTPMETHOD];
????[header appendFormat:KBLANK];
????[header appendFormat:@"/index.html"];
????[header appendFormat:KBLANK];
????[header appendFormat:HTTPVERSION];
????[header appendFormat:KENTER];
???
????[header appendFormat:HTTPHOST];
????[header appendFormat:@":"];
????[header appendFormat:hostName];
????[header appendFormat:KENTER];
????[header appendFormat:KENTER];
???
????return header;
}
?
- (NSString*)getIpAddressForHost:(NSString*) theHost
{
????struct hostent *host = gethostbyname([theHost UTF8String]);
???
????if(!host)
????{
????????herror("resolv");
????????return NULL;
????}
???
????struct in_addr **list = (struct in_addr **)host->h_addr_list;
????NSString *addressString = [NSString stringWithCString:inet_ntoa(*list[0])];
????return addressString;
}
?
- (void)Connect:(NSString *)hostName content:(NSString *)contentSended
{??
????if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
????{
????????perror("socket");
????????exit(1);
????}
???
????//NSHost *host = [NSHost hostWithName:hostName];
???
????//if(host)
????//{
????????their_addr.sin_family = AF_INET;
???????
????????//their_addr.sin_addr.s_addr = inet_addr([[host address] UTF8String]);
????????their_addr.sin_addr.s_addr = inet_addr([[self getIpAddressForHost:hostName] UTF8String]);
????????NSLog(@"getIpAddressForHost :%@",[self getIpAddressForHost:hostName]);
???????
????????their_addr.sin_port = htons(80);
????????bzero(&(their_addr.sin_zero), 8);
???????
????????int conn = connect(sockfd, (struct sockaddr*)&their_addr, sizeof(struct sockaddr));
???????
????????NSLog(@"Connect errno is :%d",conn);
????????if(conn != -1)
????????{
????????????NSLog(@"Then the conn is not -1!");
???????????
????????????NSMutableString* httpContent = [self makeHttpHeader:hostName];
???????????
????????????NSLog(@"httpCotent is :%@",httpContent);
???????????
????????????if(contentSended != nil)
????????????????[httpContent appendFormat:contentSended];
???????????
????????????NSLog(@"Sended content is :%@",httpContent);
???????????
????????????NSData *data = [httpContent dataUsingEncoding:NSISOLatin1StringEncoding];
????????????ssize_t dataSended = send(sockfd, [data bytes], [data length], 0);
???????????
????????????if(dataSended == [data length])
????????????{
????????????????NSLog(@"Datas have been sended over!");
????????????}
???????????
????????????printf("send %d bytes to %s\n",dataSended,inet_ntoa(their_addr.sin_addr));
?
????????????NSMutableString* readString = [[NSMutableString alloc] init];
????????????char readBuffer[512];
???????????
????????????int br = 0;
????????????while((br = recv(sockfd, readBuffer, sizeof(readBuffer), 0)) < sizeof(readBuffer))
????????????{
????????????????NSLog(@"read datas length is :%d",br);
???????????????
????????????????[readString appendFormat:[NSString stringWithCString:readBuffer length:br]];
???????????????
????????????????NSLog(@"Hava received datas is :%@",readString);
????????????}
???????????
????????????close(sockfd);
????????}else {
????????????UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host " stringByAppendingString:hostName] message:@"Please check the hostname in the preferences." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
????????????[alert show];
????????????[alert release];
????????}
???????
????/*
????}
????else
????{
????????UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Could not look up host " stringByAppendingString:hostName] message:@"Please check the hostname in the preferences." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
????????[alert show];
????????[alert release];
????}
?????**/
}
?
- (void)Send:(id)sender
{
????char message[7] = "aaag";
????send(sockfd,message,sizeof(message),0);
????NSLog(@"%s",message);
}
?
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
????[self Connect:@"www.baidu.com" content:nil];
???
????[super viewDidLoad];
???
????NSLog(@"view has been loaded!");
}
?
?
/*
?// Override to allow orientations other than the default portrait orientation.
?- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
?// Return YES for supported orientations
?return (interfaceOrientation == UIInterfaceOrientationPortrait);
?}
?*/
?
- (void)didReceiveMemoryWarning {
????// Releases the view if it doesn't have a superview.
????[super didReceiveMemoryWarning];
???
????// Release any cached data, p_w_picpaths, etc that aren't in use.
}
?
- (void)viewDidUnload {
????// Release any retained subviews of the main view.
????// e.g. self.myOutlet = nil;
}
?
?
- (void)dealloc {
????[super dealloc];
}
?
@end
轉(zhuǎn)載于:https://blog.51cto.com/no001/558893
總結(jié)
以上是生活随笔為你收集整理的iPhone socket 编程之BSD Socket篇的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。