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. 使用Powershell收集服务器信息

    function Get-OSInfo         ([string]$Server) {           $object = Get-WmiObject  win32_computersys ...

  2. qq

    引用:http://blog.sina.com.cn/s/blog_9e2e84050101blqz.html 腾讯QQ使用何种开发平台?                   腾讯QQ的开发分客户端软 ...

  3. truncate表hang住(等待时间较长),出现enq:RO fast object reuse等待事件

    有一个应用truncate表等待了一晚上,一个定时任务,跑了几年了,今天早上来发现昨晚没有执行完成,hang住了,查询发现等待事件 fast object reuse. 10.2.0.4的库 Bug ...

  4. Enumeration 接口

    Enumeration是遍历集合元素的一种方法. Enumeration中只有两个方法: 1.hasMoreElements()  测试此枚举是否包含更多的元素. 2.nextElement()  如 ...

  5. JS 公共方法

    1.Format函数 $.GM.Format = function (source, params) { if (arguments.length == 1) return function () { ...

  6. C++重载自增/减操作符

    作为类成员使用. 前缀是先加/减1,再取值:后缀是先取值,再加/减1. 前缀是左值,返回引用:后缀是右值,返回值. 后缀多一个int参数进行区分,用时编译器会传个没用的0作实参. 在后缀实现中调用前缀 ...

  7. python操作redis-zset

    #!/usr/bin/python #!coding: utf-8 import redis if __name__=="__main__": try: conn=redis.St ...

  8. &lt;climits&gt;头文件使用方法

    <climits>头文件定义的符号常量 CHAR_MIN  char的最小值SCHAR_MAX  signed char 最大值SCHAR_MIN   signed char 最小值UCH ...

  9. 64位win2003 IIS6运行32位的.NET程序

    做web服务迁移,从32位win2003迁移到64位win2003,数据库是32位Oracle在另外一台服务器上. 迁移之后数据库各种连不上,oracle的客户端32位的装完装64位的,odp.net ...

  10. OpenGL shader渲染贴图

    simple.vert #version core layout (location = ) in vec3 position; layout (location = ) in vec3 color; ...