Android smack之 asmack使用小总结

IM 客户端话服务器端介绍

android客户端Smack

在Android客户端需要实现IM及时通讯的功能点有

  • 保持与服务器的通信
  • 用户注册
  • 用户登录
  • 好友添加与申请、删除好友
  • 好友列表、群列表
  • 好友聊天:消息发送与接收,图片发送与接收
  • 群聊天:消息发送与接收

下面将会介绍如何去使用asmack去实现各个功能点

  • 1.保持与服务器的通信
    在两人进行聊天时,需要实时的拿到消息,必须保证对服务器的实时访问,不断地拿数据,所有需要保持一个与服务器的长连接,进行数据交互。
    所以asmack提供了一个XMPPConnection的类来保持一个与服务器的长连接(建议采用单例模式)。
XMPPConnection.DEBUG_ENABLED = true;
//配置文件  参数(服务地地址,端口号,域)
ConnectionConfiguration conConfig = new ConnectionConfiguration(
      SERVER_HOST, SERVER_PORT, SERVER_NAME);
//设置断网重连 默认为true
conConfig.setReconnectionAllowed(true);
//设置登录状态 true-为在线
conConfig.setSendPresence(true);
//设置不需要SAS验证
conConfig.setSASLAuthenticationEnabled(true);
//开启连接
XMPPConnection connection = new XMPPConnection(conConfig);
connection.connect();
//添加额外配置信息
configureConnection();
  1. 2.用户注册
    用户必须注册一个账户,作为一个用户身份识别的作用。asmack提供了一个Registration的类使用(XmppConnection是自定义的一个XMPPconnection配置工具类,下文将会经常用到),注册操作是一个网络耗时操作,要放在子线程中去执行。
Registration reg = new Registration();
//设置类型
reg.setType(IQ.Type.SET);
//发送到服务器
reg.setTo(XmppConnection.getConnection().getServiceName());
//设置用户名
reg.setUsername(account);
//设置密码
reg.setPassword(pass);
 
//设置其余属性 不填可能会报500异常 连接不到服务器 asmack一个Bug
//设置昵称(其余属性)
reg.addAttribute("name", name);
//设置邮箱(其余属性)
reg.addAttribute("email", email);
//设置android端注册
reg.addAttribute("android", "geolo_createUser_android");
//创建包过滤器
PacketFilter filter = new AndFilter(new PacketIDFilter(reg
        .getPacketID()), new PacketTypeFilter(IQ.class));
//创建包收集器
PacketCollector collector = XmppConnection.getConnection()
        .createPacketCollector(filter);
//发送包
XmppConnection.getConnection().sendPacket(reg);
//获取返回信息
IQ result = (IQ) collector.nextResult(SmackConfiguration
        .getPacketReplyTimeout());
// 停止请求results(是否成功的结果)
collector.cancel();
//通过返回信息判断
if (result == null) {
      //无返回,连接不到服务器
} else if (result.getType() == IQ.Type.ERROR) {
        //错误状态
    if (result.getError().toString()
            .equalsIgnoreCase("conflict(409)")) {
      //账户存在 409判断
    } else {
   
    }
} else if (result.getType() == IQ.Type.RESULT) {
   //注册成功跳转登录
 
}
  1. 3.用户登录
  • asmack提供了Presence的一个类
  • Presence介绍:Presence是继承自XMPP的基类Packet信息包,Presence主要有两个用途:① 告诉服务器所有客户端当前所处的状态,② 发出添加/删除好友请求;每个Presence信息包都有一个类型属性Presence.Type 如下:
  • available: 表示处于在线状态
  • unavailable: 表示处于离线状态
  • ​ subscribe: 表示发出添加好友的申请
  • unsubscribe: 表示发出删除好友的申请
  • unsubscribed: 表示拒绝添加对方为好友
  • error: 表示presence信息报中包含了一个错误消息。
// 连接服务器,用户登录
XmppConnection.getConnection().login(userStr, passStr);
// 连接服务器成功,更改在线状态
Presence presence = new Presence(Presence.Type.available);
XmppConnection.getConnection().sendPacket(presence);

2.4.好友添加与申请
分为三部分:①自己发送好友添加请求,②监听发送过来的好友请求,③处理添加好友请求(拒绝和允许)。
   (1) 发起用户添加申请使用Presence类,通过Presence.Type.subscribe表示发出添加好友的申请的状态,让服务器知道发送的数据是一个好友添加申请。

String name = et_name.getText().toString();
//设置添加好友请求
Presence subscription = new Presence(Presence.Type.subscribe);
//拼接好友全称
subscription.setTo(name + "@" + XmppConnection.SERVER_NAME);
//发送请求
XmppConnection.getConnection().sendPacket(subscription);

​    (2) 监听添加好友申请
需要解决的是如何知道服务器发送过来的是好友添加的一个请求?通过asmack提供的一个PacketFilter筛选器和PacketListener数据监听类,发起一个addPacketListener
(PacketListener,PacketListener),开启数据监听,通过PacketFilter筛选器筛选packet,监听是否是Presence.Type.subscribe添加好友申请的状态。

/**
 * 添加一个监听,监听好友添加请求。
 */
private void addSubscriptionListener() {
   
    //创建包过滤器
    PacketFilter filter = new PacketFilter() {
   
        @Override
        public boolean accept(Packet packet) {
   
            if (packet instanceof Presence) {
   
                Presence presence = (Presence) packet;
                //是好友邀请状态就返回true 向下执行
                if (presence.getType().equals(Presence.Type.subscribe)) {
   
                    return true;
                }
            }
            return false;
        }
    };
    //开启监听
    XmppConnection.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Smack是一个开源的XMPP客户端库,可用于在Android平台上构建即时通信应用程序。在使用SmackAndroid应用程序中,需要使用Smack-Android库来处理网络和连接管理。 以下是一个简单的示例代码,演示如何使用Smack-Android库连接到XMPP服务器并发送消息: 1. 添加依赖库 在项目的build.gradle文件中添加以下依赖: ``` dependencies { implementation 'org.igniterealtime.smack:smack-android-extensions:4.4.0' implementation 'org.igniterealtime.smack:smack-tcp:4.4.0' } ``` 2. 初始化连接 在应用程序启动时,需要初始化XMPPConnection对象,并且连接到XMPP服务器。 ``` XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder() .setUsernameAndPassword("username", "password") .setXmppDomain("example.com") .setHost("xmpp.example.com") .setPort(5222) .setSecurityMode(ConnectionConfiguration.SecurityMode.required) .build(); XMPPTCPConnection connection = new XMPPTCPConnection(config); try { connection.connect(); connection.login(); // Connection successful } catch (SmackException | IOException | XMPPException e) { e.printStackTrace(); // Connection failed } ``` 3. 发送消息 连接成功后,可以使用XMPPConnection对象发送消息。 ``` ChatManager chatManager = ChatManager.getInstanceFor(connection); Chat chat = chatManager.createChat("recipient@example.com"); try { chat.sendMessage("Hello, World!"); } catch (SmackException.NotConnectedException | InterruptedException e) { e.printStackTrace(); } ``` 这是一个简单的Smack-Android示例,用于连接到XMPP服务器并发送消息。当然,在实际应用程序中可能需要更多的功能和处理,但这个示例提供了一个入门的基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值