[Socket]BSD Socket网络通信
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
[Socket]BSD Socket网络通信的更多相关文章
- BSD socket编程学习
1.socket简介 BSD是实现TCP/IP协议通信的软件系统,socket是应用编程接口,为app提供使用TCP/IP协议通信的接口. 网络层IP提供点到点服务(IP地址标识),传输层TCP和UD ...
- iPhone socket 编程之BSD Socket篇
iPhone socket 编程之BSD Socket篇 收藏在进行iPhone网络通讯程序的开发中,不可避免的要利用Socket套接字.iPhone提供了Socket网络编程的接口CFSocket, ...
- 使用BSD socket编写Windows版的网络程序
我们知道BSD Socket是标准的套接字规范,那么怎么在windows使用他们呢? 我们首先要引用<winsock2.h>和ws2_32.lib 然后,执行WSAStartup #ifd ...
- 【RL-TCPnet网络教程】第20章 RL-TCPnet之BSD Socket客户端
第20章 RL-TCPnet之BSD Socket客户端 本章节为大家讲解RL-TCPnet的BSD Socket,学习本章节前,务必要优先学习第18章的Socket基础知识.有了这些基础知 ...
- 【RL-TCPnet网络教程】第19章 RL-TCPnet之BSD Socket服务器
第19章 RL-TCPnet之BSD Socket服务器 本章节为大家讲解RL-TCPnet的BSD Socket,学习本章节前,务必要优先学习第18章的Socket基础知识.有了这些基础知 ...
- 程序猿修仙之路--数据结构之你是否真的懂数组? c#socket TCP同步网络通信 用lambda表达式树替代反射 ASP.NET MVC如何做一个简单的非法登录拦截
程序猿修仙之路--数据结构之你是否真的懂数组? 数据结构 但凡IT江湖侠士,算法与数据结构为必修之课.早有前辈已经明确指出:程序=算法+数据结构 .要想在之后的江湖历练中通关,数据结构必不可少. ...
- BSD Socket~TCP~Example Code
TCP 协议实现 C版本号,可用于Mac OS X机器上执行 Server: /* Setting up a simple TCP server involves the following step ...
- socket编程 ------ BSD socket API
伯克利套接字(Berkeley sockets),也称为BSD Socket.伯克利套接字的应用编程接口(API)是采用C语言的进程间通信的库,经常用在计算机网络间的通信. BSD Socket的应用 ...
- 伯克利套接字(BSD Socket)
http://blog.csdn.net/blueman2012/article/details/6693605#socket.28.29 伯克利套接字(Berkeley sockets),也称为BS ...
随机推荐
- Java Mybatis 传参方式
一.单个参数: public List<XXBean> getXXBeanList(String xxCode); <select id="getXXXBeanList&q ...
- ASP.NET Identity 用户注册相关设定
此部分可以在 Web项目中的App_Start目录下的 IdentityConfig.cs 文件进行设置. 1.配置密码的验证逻辑 manager.PasswordValidator = new Pa ...
- primefaces 带参数的组件
分析了一下primefaces extension showcase的源码,总结一下组件传参的方式. 下面定义了一个组件,名为fourTabsDecoratorCustom.xhtml 1: < ...
- 如何诊断oracle数据库运行缓慢或hang住的问题
为了诊断oracle运行缓慢的问题首先要决定收集哪些论断信息,可以采取下面的诊断方法:1.数据库运行缓慢这个问题是常见还是在特定时间出现如果数据库运行缓慢是一个常见的问题那么可以在问题出现的时候收集这 ...
- 02_Jquery_03_类选择器
[简述] 类选择器就是通过类名(css类名)来查询元素! $(".myClass")就可以把所有包含了class="myClass"的元素查询出来 [index ...
- Codevs 1427 特种部队(双路DP)
1427 特种部队 时间限制: 1 s 空间限制: 64000 KB 题目等级 : 黄金 Gold 题目描述 Description 某特种部队接到一个任务,需要潜入一个仓库.该部队士兵分为两路,第一 ...
- Android中View绘制流程以及invalidate()等相关方法分析(转载的文章,出处在正文已表明)
转载请注明出处:http://blog.csdn.net/qinjuning 前言: 本文是我读<Android内核剖析>第13章----View工作原理总结而成的,在此膜拜下作者 .同时 ...
- a标签使用
1.发起邮件 注意:如果mailto后面同时有多个参数的话,第一个参数必须以“?”开头,后面的参数每一个都以“&”分隔. <a href="mailto:281345774@q ...
- javaScript中with的用法
1 JavaScript中的with语句的作用是为逐级的对象访问提供命名空间式的速写方式, 也就是在指定的代码区域, 直接通过节点名称调用对象 初次接触到with用法,是这样一段代码: 1 2 3 4 ...
- Delphi实用小function
Write Log // strLog : the log content need write to log file; // strFile: the compliete file path(in ...