SimpleNetworkStreams展示了如何基于Socket网络编程,实现了一个很典型的局域网内网络数据传输的场景,一个是client向server端发送本地的图片文件,另一个是client向server端下载图片到本地文件。抽取出来的一般流程:
server开启socket监听
此处IOS的一般做法是三步走:
第一步:创建系统级的socket,并绑定端口
port = 0;
fd = socket(AF_INET, SOCK_STREAM, 0);
success = (fd != -1);
if (success) {
memset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = 0;
addr.sin_addr.s_addr = INADDR_ANY;
err = bind(fd, (const struct sockaddr *) &addr, sizeof(addr));
success = (err == 0);
}
if (success) {
err = listen(fd, 5);
success = (err == 0);
}
if (success) {
socklen_t addrLen;
addrLen = sizeof(addr);
err = getsockname(fd, (struct sockaddr *) &addr, &addrLen);
success = (err == 0);
if (success) {
assert(addrLen == sizeof(addr));
port = ntohs(addr.sin_port);
}
}
这里用port=0是让系统自动随机找一个空闲端口。其他都是基于c风格对系统函数的直接调用。
第二步:用IOS的socket(CFSocket)包装系统socket
CFSocketContext context = { 0, (__bridge void *) self, NULL, NULL, NULL };
assert(self->_listeningSocket == NULL);
self->_listeningSocket = CFSocketCreateWithNative(
NULL,
fd,
kCFSocketAcceptCallBack,
AcceptCallback,
&context
);
success = (self->_listeningSocket != NULL);
if (success) {
CFRunLoopSourceRef rls;
fd = -1; // listeningSocket is now responsible for closing fd
rls = CFSocketCreateRunLoopSource(NULL, self.listeningSocket, 0);
assert(rls != NULL);
CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
CFRelease(rls);
}
这里包装socket的目的是便于后面的事件侦听和处理,把基于原生态socket的开发转到IOS的层面上来,这里accept事件侦听函数是AcceptCallback,并在单独thread中执行。
第三步:通过NSNetService发布socket
if (success) {
self.netService = [[NSNetService alloc] initWithDomain:@"local." type:@"_x-SNSUpload._tcp." name:@"Test" port:port];
success = (self.netService != nil);
}
if (success) {
self.netService.delegate = self;
[self.netService publishWithOptions:NSNetServiceNoAutoRename];
// continues in -netServiceDidPublish: or -netService:didNotPublish: ...
}
这里是基于NSNetService把先前创建的socket发布出去,便于clienti连接和请求。
client发起socket连接请求
这里是client通过前面server发布出来了netservice,发起对socket的连接:
netService = [[NSNetService alloc] initWithDomain:@"local." type:@"_x-SNSUpload._tcp." name:@"Test"];
server监听并处理数据请求
server会在accept的事件侦听的回调函数里对socket打开stream,并侦听stream上的各种IO事件:
CFStreamCreatePairWithSocket(NULL, fd, &readStream, NULL);
assert(readStream != NULL);
self.networkStream = (__bridge NSInputStream *) readStream;
CFRelease(readStream);
[self.networkStream setProperty:(id)kCFBooleanTrue forKey:(NSString *)kCFStreamPropertyShouldCloseNativeSocket];
self.networkStream.delegate = self;
[self.networkStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.networkStream open];
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
// An NSStream delegate callback that's called when events happen on our
// network stream.
{
assert(aStream == self.networkStream);
#pragma unused(aStream)
switch (eventCode) {
case NSStreamEventOpenCompleted: {
[self updateStatus:@"Opened connection"];
} break;
case NSStreamEventHasBytesAvailable: {
NSInteger bytesRead;
uint8_t buffer[32768];
[self updateStatus:@"Receiving"];
// Pull some data off the network.
bytesRead = [self.networkStream read:buffer maxLength:sizeof(buffer)];
if (bytesRead == -1) {
[self stopReceiveWithStatus:@"Network read error"];
} else if (bytesRead == 0) {
[self stopReceiveWithStatus:nil];
} else {
NSInteger bytesWritten;
NSInteger bytesWrittenSoFar;
// Write to the file.
bytesWrittenSoFar = 0;
do {
bytesWritten = [self.fileStream write:&buffer[bytesWrittenSoFar] maxLength:bytesRead - bytesWrittenSoFar];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self stopReceiveWithStatus:@"File write error"];
break;
} else {
bytesWrittenSoFar += bytesWritten;
}
} while (bytesWrittenSoFar != bytesRead);
}
} break;
case NSStreamEventHasSpaceAvailable: {
assert(NO); // should never happen for the output stream
} break;
case NSStreamEventErrorOccurred: {
[self stopReceiveWithStatus:@"Stream open error"];
} break;
case NSStreamEventEndEncountered: {
// ignore
} break;
default: {
assert(NO);
} break;
}
}
以上代码是server监听到有数据发过来时,把数据写入本地文件中,这里实际上就是把网络inputstream写入File的outputstream。这里handleevent方法是当设置了self.networkStream.delegate = self后IO事件的回调函数,handleevent里就需要根据不同的事件类型进行不同的处理。
client发送和接受数据流
client的数据处理与server类似也是通过对网络stream的事件监听来完成:
self.networkStream = output;
self.networkStream.delegate = self;
[self.networkStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.networkStream open];
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
// An NSStream delegate callback that's called when events happen on our
// network stream.
{
assert(aStream == self.networkStream);
#pragma unused(aStream)
switch (eventCode) {
case NSStreamEventOpenCompleted: {
[self updateStatus:@"Opened connection"];
} break;
case NSStreamEventHasBytesAvailable: {
assert(NO); // should never happen for the output stream
} break;
case NSStreamEventHasSpaceAvailable: {
[self updateStatus:@"Sending"];
// If we don't have any data buffered, go read the next chunk of data.
if (self.bufferOffset == self.bufferLimit) {
NSInteger bytesRead;
bytesRead = [self.fileStream read:self.buffer maxLength:kSendBufferSize];
if (bytesRead == -1) {
[self stopSendWithStatus:@"File read error"];
} else if (bytesRead == 0) {
[self stopSendWithStatus:nil];
} else {
self.bufferOffset = 0;
self.bufferLimit = bytesRead;
}
}
// If we're not out of data completely, send the next chunk.
if (self.bufferOffset != self.bufferLimit) {
NSInteger bytesWritten;
bytesWritten = [self.networkStream write:&self.buffer[self.bufferOffset] maxLength:self.bufferLimit - self.bufferOffset];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self stopSendWithStatus:@"Network write error"];
} else {
self.bufferOffset += bytesWritten;
}
}
} break;
case NSStreamEventErrorOccurred: {
[self stopSendWithStatus:@"Stream open error"];
} break;
case NSStreamEventEndEncountered: {
// ignore
} break;
default: {
assert(NO);
} break;
}
}
这里的过程与server端正好相反,是从file的Inputstream中读入数据,并写入网络的outputsteam中。
以上就是我理解的IOS中Socket网络编程的一般模式。 |
|