socket c语言实现
需要#import <sys/socket.h>、#import <netinet/in.h>、#import <arpa/inet.h>系统头文件
1.创建一个socket: socket(int,int,int)
/*
第一个参数是domain,协议域,AF_INET->IPV4,
第二个参数是type,Socket 类型,有SOCK_STREAM/SOCK_DGRAM ,
第三个参数是protocol,IPPROTO_TCP,如果是0,会自动更具第二个参数,选择合适的协议
返回值 socket
*/
int clientsocket = socket(AF_INET, SOCK_STREAM, 0);
2.连接:connect(int, const struct sockaddr *, socklen_t)
/*
参数1.socket
参数2.指向数据结构sockaddr的指针,其中包括目的端口和IP地址
参数3.结构体数据长度
返回值 0 成功/其他 错误代号
*/
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET; //协议域,
serverAddr.sin_addr.s_addr = inet_addr("192.168.2.1"); //可用本地地址
serverAddr.sin_port = htons(45678);
int connectResult = connect(clientsocket, (const struct sockaddr *)&serverAddr, sizeof(serverAddr));
if (connectResult == 0) {
NSLog(@"success...");
} else {
NSLog(@"fail...%d",connectResult);
return;
}
3.发送的方法 : send(int, const void *, size_t, int)
NSString *msg = @"hello";
ssize_t sendlen = send(clientsocket, msg.UTF8String, strlen(msg.UTF8String), 0); NSLog(@"发送了 %ld 个字节",sendlen);
4.读取的字节数
uint8_t buffer[1024];
ssize_t recvlen = recv(clientsocket, buffer, sizeof(buffer), 0);
NSLog(@"接收到了 %ld 个字节",recvlen);
//获取服务器返回的数据
NSData * data = [NSData dataWithBytes:buffer length:recvlen];
//str
NSString * str1 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"数据 %@",str1);
5.关闭socket: close(int)
close(clientsocket);
//可在终端上执行 :$ nc -lk 45678 监听端口进行调试
使用 GCDAsyncSocket
//初始化并设置代理,和线程上
self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
//连接错误
NSError *error = nil;
//开始连接
[self.socket connectToHost:SocketHost onPort:SocketPort error:&error];
//设置一个连接超市时间
//[self.socket connectToHost:SocketHost onPort:SocketPort withTimeout:CONNECTTIMEOUT error:&error]
//错误结果
if (error)
{
NSLog(@"出错了 = %@",error);
}
代理GCDAsyncSocketDelegate:的回调
//连接成功进入的方法
- (void) socket:(GCDAsyncSocket*)sock didConnectToHost:(NSString*)host port:(uint16_t)port {
NSLog(@"连接成功 host = %@, port= %d",host,post);
}
//连接失败
- (void) socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
NSLog(@"连接失败 err = %@",err);
}
//接收到的数据回调
- (void) socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"socket.返回数据 = %@",result);
}
发送消息的方法:
[self.socket writeData:data withTimeout:WRITETIMEOUT tag:WRITETAG];
断开连接:
[self.socket disconnect];
网友评论