XMPPFramework

本文介绍如何使用Swift语言实现XMPP协议,包括初始设置、安全连接建立及认证过程。通过具体代码示例,展示了如何配置XMPPStream进行连接、设置TLS安全选项、处理连接状态变化及发送接收消息。

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

XMPPFramework (swift)


xmpp初始设置

1. 搜索“jabber:iq:auth”
2. 将XMPPStream.m中的添加以下内容


state = STATE_XMPP_NEGOTIATING;
NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:auth"];

XMPPIQ *iq = [XMPPIQ iqWithType:@"get" elementID:[self generateUUID]];
[iq addChild:query];


>> XMPPElement *username = [XMPPElement elementWithName:@"username" stringValue:self.myJID.user];
>>[query addChild:username];


NSString *outgoingStr = [iq compactXMLString];
NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding];
XMPPLogSend(@"SEND: %@", outgoingStr);
numberOfBytesSent += [outgoingData length];

[asyncSocket writeData:outgoingData
withTimeout:TIMEOUT_XMPP_WRITE
tag:TAG_XMPP_WRITE_STREAM];

初始化XmppStream

    var xmppStream :XMPPStream {
        let instance = XMPPStream()
        instance?.hostName       = User.instance.hostIp
        instance?.hostPort       = User.instance.hostport
        instance?.startTLSPolicy = User.instance.tlsPolicy
        instance?.myJID          = XMPPJID.init(user: User.instance.username,
                                                domain: User.instance.hostname,
                                                resource: User.instance.resource )

        instance?.addDelegate(self, delegateQueue: DispatchQueue.main)
        DDLog.add(DDTTYLogger.sharedInstance)
        return instance!
    }

SSL/TLS安全连接

第一步:
xmppStream.connect(withTimeout: XMPPStreamTimeoutNone)
xmppStream.oldSchoolSecureConnect(withTimeout: 10) ✅

第二步:
func xmppStreamWillConnect(_ sender: XMPPStream!) {
    xmppStream.performSelector(onMainThread: Selector("setIsSecure:"), with: NSNumber.init(value: 1), waitUntilDone: true)
}

第三步:代理方法
    func xmppStream(_ sender: XMPPStream!, willSecureWithSettings settings: NSMutableDictionary!) {
        settings[GCDAsyncSocketManuallyEvaluateTrust] = NSNumber.init(value: true)
    }
    func xmppStream(_ sender: XMPPStream!, didReceive trust: SecTrust!, completionHandler: ((Bool) -> Void)!) {
        completionHandler(true);
    }
    func xmppStreamDidSecure(_ sender: XMPPStream!) {
        JIANGHAI_LOG("通过SSL/TLS安全验证")
    }

第四步:修改XMPPStream.m源文件(如果第二步无效,则添加此步骤)
1. 搜索“setIsSecure”找到此方法
2. 添加“flag = YES”,完成
- (void)setIsSecure:(BOOL)flag
{
//    flag = YES;

    dispatch_block_t block = ^{
        if(flag)
            flags |= kIsSecure;
        else
            flags &= ~kIsSecure;
    };
    if (dispatch_get_specific(xmppQueueTag))
        block();
    else
        dispatch_async(xmppQueue, block);
}    

连接代理

   func xmppStreamWillConnect(_ sender: XMPPStream!) {
        xmppStream.performSelector(onMainThread: Selector("setIsSecure:"), with: NSNumber.init(value: 1), waitUntilDone: true)
    }
    func xmppStreamDidConnect(_ sender: XMPPStream!) {
        JIANGHAI_LOG("已经连接服务器")
    }
    func xmppStreamDidDisconnect(_ sender: XMPPStream!, withError error: Error!) {

        //连接错误的情况
        let errorstring = error.localizedDescription
        if errorstring == "Socket closed by remote peer" {
            print("套接字由远程对等体关闭")
        }
        JIANGHAI_LOG(sender.myJID)
        JIANGHAI_LOG(sender.hostName)
        JIANGHAI_LOG(sender.hostPort)
        JIANGHAI_LOG("已经断开服务器")
    }
    func xmppStreamDidAuthenticate(_ sender: XMPPStream!) {
        JIANGHAI_LOG("登录成功")

    }
    func xmppStreamConnectDidTimeout(_ sender: XMPPStream!) {
        JIANGHAI_LOG("连接超时")
    }

发送授权iq

SEND:

<iq type="set">
<query xmlns="jabber:iq:access:auth">
   <username>168江海2</username>
   <ClientVer>5.2</ClientVer>
   <SystemVer>10.3</SystemVer>
   <Session_ID>92E52A2AFD79420B9F7348CE203A2C4E</Session_ID>
   <Client_IP>0.0.0.0</Client_IP>
   <server>192.168.1.168</server>
   <digest>f875ff653a3a75d7cd8fcd651bc7aa5c</digest>
</query>
</iq>


 RECV: 

 <iq xmlns="jabber:client" type="result">
 <query xmlns="jabber:iq:access:auth">
 <Message>
    <PID>28</PID>
    <AccountID>131785</AccountID>
    <JID>168江海2@115871</JID>
    <UserName>168江海2</UserName>
    <IsAdmin>0</IsAdmin>
    <IMPwd>666666</IMPwd>
    <AccountName>汇讯试用版(非正式授权)</AccountName>
    <Domain>115871</Domain>
    <AssistantURL/>
    <Host>192.168.1.32</Host>
    <FirstChanel>0</FirstChanel>
    <VisableChanels>0</VisableChanels>
    <Email/><Code_Type>1</Code_Type>
    <Session_ID>92E52A2AFD79420B9F7348CE203A2C4E</Session_ID>
    <PushOrgState>1</PushOrgState>
    <ServerVer>2.1.3</ServerVer>
    <HasAdvert>0</HasAdvert>
 </Message>
 </query>
 </iq>


 RECV: 
 <iq xmlns="jabber:client" type="error">
 <query xmlns="jabber:iq:access:auth">
 <Message>
     <Code_Type>1</Code_Type>
     <Session_ID>850E98B20158401497F4C41F3D430ADF</Session_ID>
     <Return_Code>404</Return_Code>
     <Error_Info>密码错误</Error_Info>
 </Message>
 </query>
 </iq>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值