[Socket]BSD Socket网络通信

时间:2021-09-28 01:11:23

http://blog.csdn.net/dongfengsun/article/details/4802925

文章有一些错误

#define KENTER @"/r/n"

应该为

#define KENTER @"\r\n\n"

另外原文中的buffer设置太小,只有512,地址设置为百度的话会因为太小读不到信息,改成1024即可

char readBuffer[512];

改成 char readBuffer[1024];

修改后日志输出:read datas length is :559

PS:改成google会达到令人发指的973.。。。~~

read datas length is :973

改了一些error和warning,版权归原作者所有

 #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.h

 #import "BSDHttpExampleViewController.h"

 @interface BSDHttpExampleViewController()
@end @implementation BSDHttpExampleViewController #define HTTPMETHOD @"GET"
#define HTTPVERSION @"HTTP/1.1"
#define HTTPHOST @"Host" //#define KENTER @"/r/n"
#define KENTER @"\r\n\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();
} - (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 appendString:hostName];
[header appendFormat:KENTER];
[header appendFormat:KENTER]; NSLog(@"header is %@",header); 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[]) encoding:NSASCIIStringEncoding];
//= [NSString stringWithCString:inet_ntoa(*list[0])];
return addressString;
} - (void)Connect:(NSString *)hostName content:(NSString *)contentSended
{
if((sockfd = socket(AF_INET, SOCK_STREAM, )) == -)
{
perror("socket");
exit();
} //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();
bzero(&(their_addr.sin_zero), ); int conn = connect(sockfd, (struct sockaddr*)&their_addr, sizeof(struct sockaddr)); NSLog(@"Connect errno is :%d",conn);
if(conn != -)
{
NSLog(@"Then the conn is not -1!"); NSMutableString* httpContent = [self makeHttpHeader:hostName]; NSLog(@"httpCotent is :%@",httpContent); if(contentSended != nil)
//[httpContent appendFormat:contentSended];
[httpContent appendString:contentSended]; NSLog(@"Sended content is :%@",httpContent); NSData *data = [httpContent dataUsingEncoding:NSISOLatin1StringEncoding];
ssize_t dataSended = send(sockfd, [data bytes], [data length], ); if(dataSended == [data length])
{
NSLog(@"Datas have been sended over!");
}
//printf("send %d bytes to %s\n",dataSended,inet_ntoa(their_addr.sin_addr)); printf("send %zd bytes to %s\n",dataSended,inet_ntoa(their_addr.sin_addr)); NSMutableString* readString = [[NSMutableString alloc] init];
char readBuffer[]; int br = ;
NSLog(@"size of %li",sizeof(readBuffer));
while((br = recv(sockfd, readBuffer, sizeof(readBuffer), )) < sizeof(readBuffer))
{
NSLog(@"read datas length is :%d",br); // [readString appendFormat:[NSString stringWithCString:readBuffer length:br]];
[readString appendString:[NSString stringWithCString:readBuffer encoding:kCFStringEncodingUTF8]]; 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[] = "aaag";
send(sockfd,message,sizeof(message),);
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;
} @end

BSDHttpExampleViewController.m