基于smack的即时聊天系统之登陆功能的实现

登陆功能的实现:主要思路是:1.配置连接信息2.创建XMPP连接对象;3.建立连接;4.登陆

1.配置连接信息

主要是配置服务器IP和端口号,ConnectionConfiguration()函数中第一个参数是服务器IP地址,第二个参数是端口号。第一个参数也可以写成服务器主机名,要是写为服务器主机名的话,需要修改客户端host,在hosts中添加服务器IP地址和其主机名,如下图所示。host文件在windows系统中的路径为:C:\WINDOWS\system32\drivers\etc\hosts。


配置连接信息的代码为:

org.jivesoftware.smack.ConnectionConfigurationconnConfig = new org.jivesoftware.smack.ConnectionConfiguration("openfireserver",5222);
this.config.setCompressionEnabled(true);
           
            //允许重连
            this.config.setReconnectionAllowed(true);
 
            this.config.setSendPresence(true);


2.建立XMPP连接对象

把上一步创建的connConfig作为参数创建XMPP连接对象

创建代码为:

XMPPConnection connection = newXMPPConnection(connConfig);

3.建立连接

调用XMPP连接对象的connect()方法建立连接。

代码为:

connection.connect();

4.登陆

用预先注册好的用户名和密码做为XMPP连接对象的login()方法的参数进行登陆。注意此处的用户名一定要写成userName@serverIP的形式。

登陆代码为:

connection.login("userName@serverIP","password");

用户登录的完整代码段为:

public intLogin(String userName, String passWord, String serverName)
       {
              this.config = newConnectionConfiguration(serverName, 5222);
              this.config.setCompressionEnabled(true);
             
              //允许重连
              this.config.setReconnectionAllowed(true);
 
              this.config.setSendPresence(true);
 
              configure(ProviderManager.getInstance());
 
              //创建连接对象
              this.connection = newXMPPConnection(this.config);
             
              //连接,登陆
              try
              {
                     this.connection.connect();
                     this.connection.login(
                                   userName,
                                   passWord,
                                   org.jivesoftware.spark.util.StringUtils.modifyWildcards(
                                                 this.resource).trim());
                     this.sessionManager.setServerAddress(this.connection
                                   .getServiceName());
                     this.sessionManager.initializeSession(this.connection,userName,
                                   passWord);
                     this.sessionManager.setJID(this.connection.getUser());
 
                     SparkManager.getConnection().sendPacket(
                                   newMUCPacket("logining", "com.cetc32.muc", SparkManager
                                                 .getSessionManager().getBareAddress()));
                     this.userName = userName;
                     return 0;
              } catch (XMPPException e1)
              {
                     e1.printStackTrace();
              }
              return -1;
       }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值