1、和ejabberd服务器建立连接
ConnectionConfiguration config = new ConnectionConfiguration(ConfigUtils.domin,ConfigUtils.port);
config.setSecurityMode(SecurityMode.disabled);
XMPPConnection.DEBUG_ENABLED = true;
XMPPConnection connection = new XMPPConnection(config);
connection.connect();
domin:ejabberd服务器域名或IP
port:ejabberd默认端口5222
2、注册账号到ejabberd
smack有两种方式可以注册:
a) public int registerUserToEjabberd(String userName, String password) {
// TODO Auto-generated method stub
logger.info("--------registerUserToEjabberd----------" + userName);
// ThreadPoolTools.threads.execute(new
// RegisterToEjabberdThread(userName, password));
XMPPConnection connection = ConnectionFactory.getConnection();
try {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("username", userName);
attributes.put("password", password);
attributes.put("name", userName + "@" + ConfigUtils.domin);
Registration r = new Registration();
r.setType(IQ.Type.SET);
r.setAttributes(attributes);
connection.sendPacket(r);
//过滤器,用来过滤由服务器返回的信息(即得到注册信息的内容)
PacketFilter packetFilter = new AndFilter(new PacketIDFilter(
r.getPacketID()), new PacketTypeFilter(IQ.class));
PacketCollector collector = connection
.createPacketCollector(packetFilter);
IQ result = (IQ) collector.nextResult();
if (result == null) {
logger.info("服务器没有返回任何信息");
return ConfigUtils.ERROR;
} else {
String resultString = result.getType().toString();
if (resultString.equalsIgnoreCase("result"))
logger.info(userName + "注册成功");
else if (resultString.equalsIgnoreCase("error")) {
if (result.getError().toString()
.equalsIgnoreCase("conflict(409)")) {
logger.info(userName + "用户名称已存在");
return ConfigUtils.HAVEN;
} else {
logger.info(userName + "注册失败");
return ConfigUtils.ERROR;
}
}
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getMessage());
return ConfigUtils.ERROR;
}
return ConfigUtils.OK;
}
b)public boolean regist(String username, String password,
XMPPConnection connection) {
if (connection == null)
return false;
try {
connection.getAccountManager().createAccount(username, password);
} catch (XMPPException xe) {
xe.printStackTrace();
return false;
}
return true;
}
2、smack登录ejabberd服务器
public boolean login(String username, String password,
XMPPConnection connection) {
if (connection == null)
return false;
try {
connection.login(username, password);
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
connectionListener = new TaxiConnectionListener(username,password);
connection.addConnectionListener(connectionListener);
} catch (XMPPException xe) {
xe.printStackTrace();
return false;
}
return true;
}