登陆功能的实现:主要思路是: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;
}