IOS第三十二天——Socket连接实例

本文介绍如何在iOS应用中使用AsyncSocket库实现socket连接,并通过Python编写服务器端代码进行交互。文章详细展示了设置步骤及关键代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天我们来学习下如何在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 记


评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值