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
 {
     )) == -)
     {
         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);
     )
     {
         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];
         ];

         ;
         NSLog(@"size of %li",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
 {
     ] = "aaag";
     send(sockfd,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网络通信的更多相关文章

  1. iPhone socket 编程之BSD Socket篇

    iPhone socket 编程之BSD Socket篇 收藏在进行iPhone网络通讯程序的开发中,不可避免的要利用Socket套接字.iPhone提供了Socket网络编程的接口CFSocket, ...

  2. 使用BSD socket编写Windows版的网络程序

    我们知道BSD Socket是标准的套接字规范,那么怎么在windows使用他们呢? 我们首先要引用<winsock2.h>和ws2_32.lib 然后,执行WSAStartup #ifd ...

  3. 【RL-TCPnet网络教程】第20章 RL-TCPnet之BSD Socket客户端

    第20章      RL-TCPnet之BSD Socket客户端 本章节为大家讲解RL-TCPnet的BSD Socket,学习本章节前,务必要优先学习第18章的Socket基础知识.有了这些基础知 ...

  4. 【RL-TCPnet网络教程】第19章 RL-TCPnet之BSD Socket服务器

    第19章      RL-TCPnet之BSD Socket服务器 本章节为大家讲解RL-TCPnet的BSD Socket,学习本章节前,务必要优先学习第18章的Socket基础知识.有了这些基础知 ...

  5. c#socket TCP同步网络通信

    一.socket简介 socket就是套接字,它是引用网络连接的特殊文件描述符,由三个基本要素组成: 1: AddressFamily(网络类型) 2: SocketType(数据传输类型) 3:Pr ...

  6. 程序猿修仙之路--数据结构之你是否真的懂数组? c#socket TCP同步网络通信 用lambda表达式树替代反射 ASP.NET MVC如何做一个简单的非法登录拦截

    程序猿修仙之路--数据结构之你是否真的懂数组?   数据结构 但凡IT江湖侠士,算法与数据结构为必修之课.早有前辈已经明确指出:程序=算法+数据结构  .要想在之后的江湖历练中通关,数据结构必不可少. ...

  7. BSD Socket~TCP~Example Code

    TCP 协议实现 C版本号,可用于Mac OS X机器上执行 Server: /* Setting up a simple TCP server involves the following step ...

  8. socket编程 ------ BSD socket API

    伯克利套接字(Berkeley sockets),也称为BSD Socket.伯克利套接字的应用编程接口(API)是采用C语言的进程间通信的库,经常用在计算机网络间的通信. BSD Socket的应用 ...

  9. Python的网络编程[0] -&gt; socket[0] -&gt; socket 与 TCP / UDP

    Socket socket 简述 / socket Abstract 网络进程通信与 socket 网络中进程之间如何通信,首要解决的问题是如何唯一标识一个进程,否则通信无从谈起.在本地可以通过进程 ...

随机推荐

  1. NotSupportedException-无法将类型“System.DateTime”强制转换为类型“System.Object”

    几张图就可以说明一切 2015-03-29 21:54:09,206 [77] ERROR log - System.NotSupportedException: 无法将类型“System.DateT ...

  2. NSFileManager计算文件/文件夹大小

    在一些软件中,一般都会给用户展现当前APP的内存,同时用户可以根据自己的需要来清除缓存的内容.一般而言,文件夹是没有大小这个属性的,所以需要遍历文件夹的内容来计算文件夹的大小,下面用NSFileMan ...

  3. GitBook – 使用 GitHub 和 Markdown 制作书籍

    GitBook 是一个命令行工具(也是 Node.js 库),让你能够使用 GitHub/Git 和 Markdown 构建出美丽的编程书籍,可以包含互动的练习.GitBook 支持使用多种语言构建书 ...

  4. Head First Design Patterns学习笔记-观察者模式

    认识观察者模式 首先来看看报纸订阅的过程 1.报社的业务就是出版报纸 2.向某家报社订阅报纸,只要他们有新报纸出版,就会送过来,只要你是他们的订户 3.当你不想再看报纸的时候,取消订阅,他们就不会再送 ...

  5. CVE爬虫抓取漏洞URL

    String url1="http://www.cnnvd.org.cn/vulnerability/index/vulcode2/tomcat/vulcode/tomcat/cnnvdid ...

  6. MSP430单片机的中断

    这篇文章是从网上转载过来的,原文章地址:http://www.21ic.com/jichuzhishi/mcu/questions/2012-12-21/154794.html 中断是MSP430微处 ...

  7. 安装node/npm/webpack步骤

    nodejs软件的下载地址:https://nodejs.org/en/ 1.只要安装好了nodejs,就自动安装好了npm包. 2.在cmd中通过命令node -version查看是否安装好node ...

  8. Java面试题2--数据类型

    1. Java的数据类型? 2. Java的封装类型? 3. 基本类型和封装类型的区别? 基本类型只能按值传递,而对应的封装类是按引用传递的. 基本类型是在堆栈上创建的,而所有的对象类型都是在堆上创建 ...

  9. oracle数据恢复方法

    https://www.cnblogs.com/hqbhonker/p/3977200.html

  10. Java学习笔记24(Map集合)

    Map接口: Map接口与Collection接口无继承关系. 区别:Collection中的元素是孤立的,一个一个存进去的. Map作为一个映射集合,每一个元素包含Key-value对(键-值对). ...