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
//
// 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
相关文章推荐
- 宋体、代码-iOS网络编程实践--NSStream实现TCP Socket iPhone客户端-by小雨
- iphone socket编程之AsyncSocket使用说明
- iPhone开发之网络编程 AsyncSocket
- 玩转iPhone网络通讯之BSD Socket篇
- iphone使用开源代码Asyncsocket进行socket编程 之二
- iPhone网络通讯之BSD Socket篇(手把手教你iphone开发)
- iphone开发之轻松搞定原生socket 编程,阻塞与非阻塞,收发自如
- iPhone开发Socket编程使用开源代码之AsyncSocket
- iphone使用开源代码Asyncsocket进行socket编程
- iPhone的Socket编程使用开源代码之AsyncSocket(转)
- iOS网络编程实践--NSStream实现TCP Socket iPhone客户端
- iphone开发之轻松搞定原生socket 编程,阻塞与非阻塞,收发自如
- [iPhone-NetWork]BSD Socket API 函数参考大全
- 轻松搞定iPhone socket 编程 用代码说话(iphone开发入门 4)
- iPhone网络编程之CocoaAsyncSocket(转载)
- iPhone socket 编程之BSD Socket篇
- iphone使用开源代码Asyncsocket进行socket编程
- 玩转iPhone网络通讯之BSD Socket篇
- iPhone开发之网络编程 AsyncSocket
- iPhone socket 编程之BSD Socket篇