iOS socket Stream 服务器端 及 客户端 演示
iOS socket Stream
测试环境,mac osx 10.8
一:建立服务器端
由于mac osx10.8 已经集成 python2和 Twisted,我们可以直接利用此,构建一个简单的socket 服务器
如下测试一个简单的聊天 socket
并,定义,加入聊天时发送:iam:用户名
发送信息时:msg:信息
终端:vim server.py 回车,copy入如下代码
from twisted.internet.protocol import Factory, Protocol from twisted.internet import reactor class IphoneChat(Protocol): def connectionMade(self): self.factory.clients.append(self) print "clients are ", self.factory.clients def connectionLost(self, reason): self.factory.clients.remove(self) def dataReceived(self, data): a = data.split(':') print a if len(a) > 1: command = a[0] content = a[1] msg = "" if command == "iam": self.name = content msg = self.name + " has joined" elif command == "msg": msg = self.name + ": " + content print msg for c in self.factory.clients: c.message(msg) def message(self, message): self.transport.write(message + ' ') factory = Factory() factory.clients = [] factory.protocol = IphoneChat reactor.listenTCP(80, factory) print "Iphone Chat server started" reactor.run()
上面 server.py建立好之后
在终端:sudo python server.py 开启服务器 看到 Iphone Chat server started ,开启成功;
二:终端测试服务器
1:在上面服务器开启成功之后;
2:打开另一个终端:telnet localhost 80 回车,即可看到 socket 连接成功;Connected to localhost.
3: 在终端里面输入测试信息:iam:cc 回车; msg:hi 回车;即可以两个终端下看到实时的信息传递情况;
4:再新建立一个终端:telnet localhost 80 即可实现,多个client 连接 服务器 socket
三:在iOS 端建立 socket 连接 client
1:先建立两个实例变量,并实现代理
@interface ViewController : UIViewController<NSStreamDelegate> { NSInputStream *inputStream; NSOutputStream *outputStream; } @end
2:建立 socket 与本地 socket 服务器
- (void)initNetworkCommunication { CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", 80, &readStream, &writeStream); inputStream = (__bridge NSInputStream *)readStream; outputStream = (__bridge NSOutputStream *)writeStream; [inputStream setDelegate:self]; [outputStream setDelegate:self]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream open]; [outputStream open]; }