iOS socket Stream 服务器端 及 客户端 演示

iOS socket Stream

测试环境,mac osx 10.8

一:建立服务器端

  由于mac osx10.8 已经集成 python2和 Twisted,我们可以直接利用此,构建一个简单的socket 服务器

  如下测试一个简单的聊天 socket

  并,定义,加入聊天时发送:iam:用户名

  发送信息时:msg:信息

 终端:vim server.py  回车,copy入如下代码

iOS socket Stream 服务器端 及 客户端 演示
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 + \n)


factory = Factory()
factory.clients = []
factory.protocol = IphoneChat
reactor.listenTCP(80, factory)
print "Iphone Chat server started"
reactor.run()
iOS socket Stream 服务器端 及 客户端 演示

上面 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:先建立两个实例变量,并实现代理 

iOS socket Stream 服务器端 及 客户端 演示
@interface ViewController : UIViewController<NSStreamDelegate>

{
    NSInputStream *inputStream;
    NSOutputStream *outputStream;
}

@end
View Code

2:建立 socket 与本地 socket 服务器

iOS socket Stream 服务器端 及 客户端 演示
- (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];
    

    
}
View Code

3:测试加入聊天和发送聊天

iOS socket Stream 服务器端 及 客户端 演示
- (void)joinChatServer
{
    NSString *name=@"cc";
    NSString *response = [NSString stringWithFormat:@"iam:%@",name];
    NSData *data = [[NSData alloc]initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]];
    
    [outputStream write:[data bytes] maxLength:[data length]];
    
    
    
}


- (void)sendMesage
{
    NSString *mess=@"hello world";
    NSString *response = [NSString stringWithFormat:@"msg:%@",mess];
    NSData *data = [[NSData alloc]initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]];
    
    [outputStream write:[data bytes] maxLength:[data length]];
}
View Code

4:在代理中接收socket传递的信息

iOS socket Stream 服务器端 及 客户端 演示
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
    
    switch (streamEvent) {
            
        case NSStreamEventOpenCompleted:
            NSLog(@"Stream opened");
            break;
            
        case NSStreamEventHasBytesAvailable:
            if (theStream == inputStream) {
                
                uint8_t buffer[1024];
                int len;
                
                while ([inputStream hasBytesAvailable]) {
                    len = [inputStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0) {
                        
                        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
                        
                        if (nil != output) {
                            NSLog(@"server said: %@", output);
                        }
                    }
                }
            }
            break;
            
        case NSStreamEventErrorOccurred:
            NSLog(@"Can not connect to the host!");
            break;
            
        case NSStreamEventEndEncountered:
            break;
            
        default:
            NSLog(@"Unknown event");
    }
    
}
View Code

 

四:参考:

http://www.raywenderlich.com/3932/networking-tutorial-for-ios-how-to-create-a-socket-based-iphone-app-and-server

https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/UsingSocketsandSocketStreams.html

http://www.cnblogs.com/kesalin/archive/2013/04/14/ios_cfnetwork.html

https://developer.apple.com/library/ios/qa/qa1652/_index.html

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html

iOS socket Stream 服务器端 及 客户端 演示,布布扣,bubuko.com

iOS socket Stream 服务器端 及 客户端 演示

上一篇:Android开发之使用广播监听网络状态变化


下一篇:什么是Cookie对象,Session对象,Application对象。