[XMPP]简易的聊天室实现[一]
这几天开始学xmpp,先做了超级简易版,以后慢慢加强
因为是简易的,服务器也是简易的,用py脚本写的服务器
因为我是拿来用的就不放上源码了
首先StoryBoard上面拖一些控件,都是简单的,然后加一下约束,这里就不详细说了
比较要注意的是这里我们把输入框容器view的底部约束连线,等下会用到
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewConstraint;
连接服务器部分我们要定义输入输出流然后加入到runloop中去,记得结束连接的时候要移除
- (IBAction)connentToHost:(UIBarButtonItem *)sender
{
NSString *host = @"10.82.197.21";
int port = 12345;
CFReadStreamRef redStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &redStream, &writeStream);
_inputStream = (__bridge NSInputStream *)(redStream);
_outputStream = (__bridge NSOutputStream *)(writeStream);
_inputStream.delegate = self;
_outputStream.delegate = self;
[_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[_inputStream open];
[_outputStream open];
}
[_inputStream close];
[_outputStream close];
[_inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
然后是登陆,要把NSString转换生NSData
- (IBAction)loginBtnClick:(UIBarButtonItem *)sender
{
//登陆发送数据格式为“iam:username”
//发送消息数据格式为“msg:message”
NSString *loginStr = @"iam:HJ";
NSData *data = [loginStr dataUsingEncoding:NSUTF8StringEncoding];
[_outputStream write:data.bytes maxLength:data.length];
}
我们会实现输入框的代理
UITextFieldDelegate
这样就能够监听确定按钮来发送消息了
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSString *msgStr = [NSString stringWithFormat:@"msg:%@",textField.text];
NSData *data = [msgStr dataUsingEncoding:NSUTF8StringEncoding];
[_outputStream write:data.bytes maxLength:data.length];
[self reloadData:msgStr];
textField.text = nil;
return YES;
}
这里输入框位置调整的方法比较新,首先我们监听键盘通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbFrmWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
然后在键盘将要弹出的时候改变约束的值
- (void)kbFrmWillChange:(NSNotification *)noti
{
//获取窗口高度
CGFloat windowsH = [UIScreen mainScreen].bounds.size.height;
//键盘结束的y
CGRect kbEnfFrm = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
self.inputViewConstraint.constant = windowsH - kbEnfFrm.origin.y;
}
代码其他部分就不细说了,我把代码上传了github了:
https://github.com/hjandyz/XMPP