/*
Socket 基础知识
1、 INADDR_ANY就是指定地址为0.0.0.0的地址,这个地址事实上表示不确定地址,或“所有地址”、“任意地址”。 一般来说,在各个系统中均定义成为0值。
2、 INADDR_ANY指的是所有ip,即连接本机任何一个ip地址都可以连接上
3、 sin_family指代协议族,在socket编程中只能是AF_INET
4、 sin_port存储端口号(使用网络字节顺序),需要大于1024.
5、 sin_addr存储IP地址,使用in_addr这个数据结构
6、 sin_zero是为了让sockaddr与sockaddr_in两个数据结构保持大小相同而保留的空字节。
7、 s_addr按照网络字节顺序存储IP地址
8、 sockaddr_in和sockaddr是并列的结构,指向sockaddr_in的结构体的指针也可以指向sockaddr的结构体,并代替它。也就是说,你可以使用sockaddr_in建立你所需要的信息。
*/
上一篇我们学习了如何编写服务器,我们将在这一篇学习如何编写客户端
ViewController.h代码如下:
#import@interface QQViewController : UIViewController{ int toServerSocket;}@property(strong,nonatomic) IBOutlet UITextField* textIp;@property(strong,nonatomic) IBOutlet UITextField* textPort;@property(strong,nonatomic) IBOutlet UITextField* textMessage;-(IBAction)btnConnServer:(id)sender;-(IBAction)btnSendMessage:(id)sender;-(IBAction) hiddenKeyboard:(id)sender;-(void) sendToServer:(NSString*) message;@end
ViewController.m代码如下:
#import "QQViewController.h"#include#include #include #include #include #include #include #define BUFFER_SIZE 1024@interface QQViewController ()@end@implementation QQViewController@synthesize textIp;@synthesize textMessage;@synthesize textPort;- (void)viewDidLoad{ [super viewDidLoad]; toServerSocket = 0;}- (void)viewDidUnload{ [super viewDidUnload]; if(toServerSocket !=0){ [self sendToServer:@"-"]; close(toServerSocket); }}-(IBAction)btnConnServer:(id)sender{ NSLog(@"conn server..."); if(toServerSocket !=0){ [self sendToServer:@"-"]; close(toServerSocket); } struct hostent *he; struct sockaddr_in server; NSString *ip = self.textIp.text; NSString *port = self.textPort.text; if((he = gethostbyname([ip cStringUsingEncoding:NSUTF8StringEncoding])) == NULL) { printf("gethostbyname error/n"); //exit(1); } if((toServerSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) { printf("socket() error /n"); //exit(1); } bzero(&server, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons([port intValue]); server.sin_addr = *((struct in_addr *)he->h_addr); if(connect(toServerSocket, (struct sockaddr *)&server, sizeof(server)) == -1) { printf("\n connetc() error "); // exit(1); }}-(IBAction)btnSendMessage:(id)sender{ [self sendToServer:textMessage.text];}-(void) sendToServer:(NSString*) message{ NSLog(@"send message to server..."); char buffer[BUFFER_SIZE]; bzero(buffer, BUFFER_SIZE); //Byte b; const char* talkData = [ message cStringUsingEncoding:NSUTF8StringEncoding]; //发送buffer中的字符串到new_server_socket,实际是给客户端 send(toServerSocket,talkData,[message length],0);}- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{ return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);}-(void) hiddenKeyboard:(id)sender{ [sender resignFirstResponder];}@end
代码下载地址: