1. 程式人生 > >IOS第三十二天——Socket連線例項

IOS第三十二天——Socket連線例項

今天我們來學習下如何在IOS中使用socket連線,幸運的是,感謝github,我們找到一個第三方的開源類庫可以很方便的幫我們實現這個,接下來我們就來實現一下,不過這次雖然有圖形介面,但我們沒有新增任何東西。

首先說一下這裡server端是用python寫的,簡單的寫了一個,程式碼如下:

#!/usr/bin/env python
#-*-coding:utf-8-*-

import socket
def getInfo():
	address=('127.0.0.1',8888)
	sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	sock.bind(address)
	sock.listen(5)
	
	client,addr=sock.accept()
	print 'connected with',addr
	
	client.send(b'Hi there')
	ra=sock.recv(1024)
	print ra
	
	client.close()
	sock.close()
#end def

if __name__=='__main__':
	getInfo()

因為mac系統下預設是安裝了python的,正好也能把python練習一下,活學活用。

然後說下我們使用的第三方庫,AsyncSocket ,那麼我們去git上把它clone出來。

接著我們就開始寫IOS端了,首先新建一個專案,新增CFNetwork.framework到專案中。

然後在我們的專案中把AsyncSocket新增進來:


然後我們在ETViewController.h中新增以下程式碼:

#import <UIKit/UIKit.h>
#import "AsyncSocket.h"

@interface ETViewController : UIViewController
{
    AsyncSocket *asyncSocket;
}
接下來是ETViewController.m中的程式碼:
#import "ETViewController.h"

@interface ETViewController ()

@end

@implementation ETViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
    NSError *err = nil;
    if(![asyncSocket connectToHost:@"127.0.0.1" onPort:8888 error:&err])
    {
        NSLog(@"Error: %@", err);
    }
}
//建立連線
-(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"onScoket:%p did connecte to host:%@ on port:%d",sock,host,port);
    [sock readDataWithTimeout:1 tag:0];
}

//讀取資料
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *aStr=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"aStr==%@",aStr);
    [aStr release];
    NSData *aData=[@"Hi there" dataUsingEncoding:NSUTF8StringEncoding];
    [sock writeData:aData withTimeout:-1 tag:1];
    [sock readDataWithTimeout:1 tag:0];
}

//是否加密
-(void)onSocketDidSecure:(AsyncSocket *)sock
{
    NSLog(@"onSocket:%p did go a secure line:YES",sock);
}

//遇到錯誤時關閉連線
-(void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(@"onSocket:%p will disconnect with error:%@",sock,err);
}

//斷開連線
-(void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    NSLog(@"onSocketDidDisconnect:%p",sock);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    [asyncSocket release];
    [super dealloc];
}
@end

這些完成了之後呢,我們就可以開始測試了,那麼首先要啟動python寫的server,進入終端,進入到pyServer.py所在的目錄,然後輸入如下命令來啟動server:
python pyServer.py

之後回車,server就啟動了,然後我們就可以啟動IOS模擬器來進行除錯了,可以收到如下圖所示的迴應資訊,說明我們成功了:


OK,今天的知識就學到這裡,那麼隨著時間的積累,同時自己也在學Tornado,那麼希望可以用python為IOS寫出更好的服務端。

2013年06月23日,Eric.Tang 記