TCP/UDP区别

1.定义:

TCP(Transmission Control Protocol,传输控制协议)是基于连接的协议,也就是说,在正式收发数据前,必须和对方建立可靠的连接。

UDP(User Data Protocol,用户数据报协议)是与TCP相对应的协议。它是面向非连接的协议,它不与对方建立连接,而是直接就把数据包发送过去

使用的类库:AsyncUdpSocket和GCDAsyncUdpSocket(最普遍的用于多线程的)

2.TCP/UDP区别:

                           TCP                    UDP  

是否连接:           面向连接           非面向连接(不连接)

可靠性:              可靠                 不可靠

应用场合:           传输大量数据      少量数据传输

传输速度:            慢                   快

参考:

TCP/UDP协议:http://baike.baidu.com/link?url=XMazjhhXpUmEowHE7eI6vAx35Hpl9BvewKMRK1zYqx0hlUNraiFBrDOdhT_kUUEucm5mFLQe0_80g1BemCrOs_

 3.UDP的操作步骤:

首先是在viewWillAppear:(BOOL)animated方法中打开UDPServer,然后通过UPD发送消息

-(void)viewWillAppear:(BOOL)animated{

[self openUDPServer];

[self sendMassage:message];

}

//建立基于UDP的Socket连接

-(void)openUDPServer{

//初始化udp

AsyncUdpSocket *tempSocket=[[AsyncUdpSocket alloc] initWithDelegate:self];

self.udpSocket=tempSocket;

[tempSocket release];

//绑定端口

NSError *error = nil;

[self.udpSocket bindToPort:4333 error:&error];

    

//发送广播设置

 [self.udpSocket enableBroadcast:YES error:&error];

    

//加入群里,能接收到群里其他客户端的消息

 [self.udpSocket joinMulticastGroup:@"224.0.0.2" error:&error];

    

//启动接收线程

[self.udpSocket receiveWithTimeout:-1 tag:0];

  

}

 

//通过UDP,发送消息

-(void)sendMassage:(NSString *)message

{   

    

NSDate *nowTime = [NSDate date];

 

NSMutableString *sendString=[NSMutableString stringWithCapacity:100];

[sendString appendString:message];

//开始发送

BOOL res = [self.udpSocket sendData:[sendString dataUsingEncoding:NSUTF8StringEncoding] //编译

toHost:@"224.0.0.2" //服务器

port:4333 //端口

withTimeout:-1 //超时

 tag:0];

 //如果发送失败就弹出框提示

   if (!res) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"

message:@"发送失败"

  delegate:self

  cancelButtonTitle:@"取消"

  otherButtonTitles:nil];

[alert show];

[alert release];

}

 

if ([self.chatArray lastObject] == nil) {

self.lastTime = nowTime;

[self.chatArray addObject:nowTime];

}

 //NSTimeInterval获取时间间隔 

NSTimeInterval timeInterval = [nowTime timeIntervalSinceDate:self.lastTime];

if (timeInterval >5) {

self.lastTime = nowTime;

[self.chatArray addObject:nowTime];

}

 

UIView *chatView = [self bubbleView:[NSString stringWithFormat:@"%@:%@", NSLocalizedString(@"me",nil), message] 

  from:YES];

[self.chatArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:message, @"text", @"self", @"speaker", chatView, @"view", nil]];

 //更新数据

[self.chatTableView reloadData];

//屏幕滚动

[self.chatTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.chatArray count]-1 inSection:0

  atScrollPosition:UITableViewScrollPositionBottom 

  animated:YES];

}

//使用UDP的delegate方法

#pragma mark UDP Delegate Methods

//收到数据后的处理

- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port

{   

    [self.udpSocket receiveWithTimeout:-1 tag:0];

    NSLog(@"host---->%@",host);

 

    //收到自己发的广播时不显示出来

    NSMutableString *tempIP = [NSMutableString stringWithFormat:@"::ffff:%@",myIP];

    if ([host isEqualToString:self.myIP]||[host isEqualToString:tempIP])

    {   

//        return YES;

    }

    

   //接收到数据回调,用泡泡VIEW显示出来

 

NSString *info=[[[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding] autorelease];

 

    UIView *chatView = [self bubbleView:[NSString stringWithFormat:@"%@:%@", host, info] 

  from:NO];

 

[self.chatArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:info, @"text", @"other", @"speaker", chatView, @"view", nil]];

 

[self.chatTableView reloadData];

[self.chatTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.chatArray count]-1 inSection:0

  atScrollPosition:UITableViewScrollPositionBottom 

  animated:YES];

//已经处理完毕

return YES;

}

 

//无法发送

- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error

{

//无法发送时,返回的异常提示信息

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"

message:[error description]

  delegate:self

  cancelButtonTitle:@"取消"

  otherButtonTitles:nil];

[alert show];

[alert release];

 

}

 

//无法接收

- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error

{   

//无法接收时,返回异常提示信息

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"

message:[error description]

  delegate:self

  cancelButtonTitle:@"取消"

  otherButtonTitles:nil];

[alert show];

[alert release];

}

 

原文地址:https://www.cnblogs.com/yuyu-2012/p/4813364.html