您的位置:首页 > 编程语言

iPhone socket 编程之BSD Socket篇

2011-05-04 10:42 585 查看
最后为了造福大家,笔者附上完整 的代码,头文件如下:

//
// 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

实现文件如下:

//
// 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, images, 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本文出自 “人生得意须尽欢” 博客,请务必保留此出处http://no001.blog.51cto.com/1142339/558893
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: