[XMPP]简易的聊天室实现[一]

本文介绍如何使用Python编写简易XMPP服务器和客户端,包括连接服务器、登陆、输入输出流管理以及输入框代理实现消息发送,并通过键盘通知调整输入框位置。

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

这几天开始学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”

    //发送消息数据格式为“msgmessage”

    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

 

转载于:https://www.cnblogs.com/hanjian/p/4364799.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值