谈到socket编程,业内已经有了很多socket第三方很好用的框架 CocoaSyncSocket ,socketIO, 如果要了解socket的原理,还是从用c语言建立一个简单socket开始
1.建立链接
//SOCK_STREAM 代表用TCP 连接
//AF_INET 代表是ipv4网络
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
NSLog(@"创建失败");
}else{
//绑定地址和端口
int port = 1234;
NSString *serverIP = @"127.0.0.1";
struct sockaddr_in server_addr;
server_addr.sin_len = sizeof(struct sockaddr_in);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = inet_addr(serverIP.UTF8String);
bzero(&(server_addr.sin_zero), 8);
//创建新的socket
int aResult = connect(server_socket, (struct sockaddr*)&server_addr, sizeof(struct sockaddr_in));
if (aResult == -1) {
NSLog(@"链接失败");
}else{
self.server_socket = server_socket;
if(self.sockectThread == nil) {
// 异步线程接受客户端的链接
self.sockectThread = [[NSThread alloc] initWithTarget:self selector:@selector(acceptFromServer) object:nil];
}
}
}
2.发送数据
(void)sendMsg:(NSString*)msg {
/*send 方法参数
参数1:客户端的socket
参数2: 要发送的内容
参数3: 要发送内容的长度,字节
发送标示位 传0即可
*/
char *buf[1024] = {0};
const char *p1 = (char*)buf;
p1 = [msg cStringUsingEncoding:NSUTF8StringEncoding];
send(self.server_socket, p1, 1024, 0);
}
3.接收数据
- (void)acceptFromServer{
@autoreleasepool {
NSLog(@"current thread = %@", [NSThread currentThread]);
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
[runLoop runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]];
//死循环接收数据
while (1) {
//接受服务器传来的数据
char buf[1024];
long iReturn = recv(self.server_socket, buf, 1024, 0);
if (iReturn>0) {
NSString *str = [NSString stringWithCString:buf encoding:NSUTF8StringEncoding];
//通知代理处理事情
}else if (iReturn == -1){
NSLog(@"接受失败-1");
break;
}
}
}
}
这就是ios 客户端如果要用源码实现一个最简单的socket需要的代码,其中有好多问题,发送数据的时候如果数据超过了1024个字节,就会产生丢失。接收socket数据的时候没有处理,安全性问题等等。
通过Socket编程更深刻了解Socket原理,用CocoaSyncSocket,写了一个Socket 心跳连接,断包,黏包,断线重连的demo https://github.com/maoemao/socketDemo