简易UDP传输

 

ViewController.h

 1 #import <UIKit/UIKit.h>
 2 #import "AsyncUdpSocket.h"
 3 
 4 @interface ViewController : UIViewController
 5 <AsyncUdpSocketDelegate>
 6 {
 7     IBOutlet UITextField *ipField;
 8     IBOutlet UITextField *sendField;
 9     IBOutlet UITextView *contentView;
10     
11     AsyncUdpSocket *recvSocket;
12     AsyncUdpSocket *sendSocket;
13 }
14 
15 -(IBAction)sendText:(id)sender;
16 
17 @end

 

ViewController.m

 1 #import "ViewController.h"
 2 
 3 @implementation ViewController
 4 
 5 #pragma mark - viewDidLoad
 6 
 7 - (void)viewDidLoad
 8 {
 9     [super viewDidLoad];
10     
11     //服务端
12     recvSocket = [[AsyncUdpSocket alloc]initWithDelegate:self];
13     //客户端
14     sendSocket = [[AsyncUdpSocket alloc]initWithDelegate:self];
15     
16     //服务端开始等待别的客户端的连接
17     //65535   >5000
18     [recvSocket bindToPort:5888 error:nil];
19     [sendSocket bindToPort:5999 error:nil];
20     
21     //等待接受数据
22     [recvSocket receiveWithTimeout:-1 tag:100];
23     //什么时候接受到了数据
24 }
25 
26 #pragma mark - AsyncUdpSocketDelegate
27 //调用这个方法的时候证明接收到了数据
28 -(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port
29 {
30     NSString *str = [[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease];
31     contentView.text = [NSString stringWithFormat:@"%@\n%@:%@",contentView.text,host,str];
32     [recvSocket receiveWithTimeout:-1 tag:100];
33     return YES;
34 }
35 //这里就发送成功了
36 -(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag
37 {
38 }
39 
40 #pragma mark - .h event
41 -(void)sendText:(id)sender
42 {
43     NSData *data = [sendField.text dataUsingEncoding:NSUTF8StringEncoding];
44     [sendSocket sendData:data toHost:ipField.text port:5888 withTimeout:60 tag:100];
45     
46 }
47 @end

 

转载于:https://www.cnblogs.com/liushong/archive/2013/01/29/2881180.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值