=====================希望对大家有所帮助,仅此而已================
/*
AsyncSocket 聊天用的。。。-------》是可以通过ip给某个设备发送消息,关键是如何找到ip,问题就解决了。------》ip其实是通过登陆来获取的。只要是登陆用户服务器就可以把id号码和ip一一绑定了。
聊天的原理:例如A发送给B消息。
1.A先发送给服务器消息包含(B的id号码和要发送的内容)。
2.如果B不在线,服务器利用推送通知推送给B一个消息。当B登陆后会传给服务器自己的id和ip(外网内网都有)
服务器就可以把之前A发来的消息再发给B了。并注明是A发的。
3.B就收到了A的消息。
其实整个过程是 socket和推送共同完成的。。。主要工作在后台。,,,手机端功能并不复杂。
*/
#define kScreenHeight [[UIScreen mainScreen] bounds].size.height
#define kScreenWidth [[UIScreen mainScreen] bounds].size.width
#import "FirstViewController.h"
@interfaceFirstViewController ()
@end
@implementation FirstViewController
- (void)viewDidLoad {
[superviewDidLoad];
self.title = @"聊天页面";
self.navigationController.navigationBarHidden = YES;
self.view.backgroundColor = [UIColorlightGrayColor];
self.myTextField = [[UITextFieldalloc]initWithFrame:CGRectMake(0, 50, kScreenWidth - 60, 40)];
self.myTextField.backgroundColor = [UIColorwhiteColor];
[self.viewaddSubview:self.myTextField];
self.myTextView = [[UITextViewalloc]initWithFrame:CGRectMake(self.myTextField.frame.origin.x, self.myTextField.frame.origin.y + 60,kScreenWidth, kScreenHeight - 100)];
[self.viewaddSubview:self.myTextView];
self.myButton = [UIButtonbuttonWithType:UIButtonTypeCustom];
self.myButton.frame = CGRectMake(self.myTextField.frame.size.width, 50, 50, 40);
[self.myButtonsetTitle:@"发送"forState:UIControlStateNormal];
[self.myButtonaddTarget:selfaction:@selector(goAction) forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:self.myButton];
///1.创建发送套接字
sendUdpSocket = [[AsyncUdpSocketalloc]initWithDelegate:self];
reservedUdpSocket = [[AsyncUdpSocketalloc]initWithDelegate:self];
[reservedUdpSocketbindToPort:0x1234error:nil];
[reservedUdpSocketreceiveWithTimeout:-1tag:200];//200表示
///2.绑定端口(可选的)
///发送消息。通过按钮的事件。
}
-(void)goAction{
NSString *ip = @"192.168.7.101";
NSString *context = self.myTextField.text;
UInt16 port = 0x1234; //// > 1024 < 2`16-1
NSData *sendData = [context dataUsingEncoding:NSUTF8StringEncoding];
[sendUdpSocketsendData:sendData toHost:ip port:port withTimeout:-1tag:100];
}
-(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
if (tag == 100) {
///证明tag==100的标记发送完成了
NSLog(@"证明tag==100的标记发送完成了");
}
}
-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
NSLog(@"tag====%ld",tag);
[reservedUdpSocketreceiveWithTimeout:-1tag:200];//200表示
NSString *tempS = [[NSStringalloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *resultS = [NSStringstringWithFormat:@"\n%@%@%@\n",@"接收到: ",tempS,self.myTextView.text];
self.myTextView.text = resultS;
returnYES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.myTextFieldresignFirstResponder];
[self.myTextViewresignFirstResponder];
}
-(void)viewWillAppear:(BOOL)animated{
[superviewWillAppear:animated];
}
@end