package cn.sunsharp.ycpn.client;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.provider.ProviderManager;
/**
* 客户端采用基于java的XMPP协议包asmack(该包依赖于openfire下的开源项目smack)。
* 通过该协议包提供的 XMPPConnetcion 类与服务器建立持久连接,并通过该连接进行用户注册和登录认证,以及接受服务器消息。
* @author sunsharp
*
*/
public class XmppManager {
private String userName="";
private String password="";
private String xmppHost="192.168.1.106";
private int xmppPort=9527;
private XMPPConnection connection; // asmack和server端的连接类
public static void main(String[] args) {
XmppManager xm = new XmppManager();
/*XmppManager.ConnectTask xc = xm.new ConnectTask();
xc.run();*/
xm.connect();
}
public void connect(){
if(!isConnect()){
ConnectionConfiguration connConfig = new ConnectionConfiguration(xmppHost, xmppPort);
//connConfig.setSecurityMode(SecurityMode.disabled);
connConfig.setSecurityMode(SecurityMode.required);
connConfig.setSASLAuthenticationEnabled(false);
connConfig.setCompressionEnabled(false);
try {
XMPPConnection xc = new XMPPConnection(connConfig);
xc.connect(); // 建立和server端的额连接
this.setConnection(xc);
// namespace为androidpn:iq:notification
ProviderManager.getInstance().addIQProvider("notification",
"androidpn:iq:notification",new NotificationIQProvider());
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 用于连接的内部类
* @author sunsharp
*/
/* private class ConnectTask implements Runnable{
final XmppManager xmppManager;
private ConnectTask(){
this.xmppManager = XmppManager.this;
}
@Override
public void run() {
if(!xmppManager.isConnect()){
ConnectionConfiguration connConfig = new ConnectionConfiguration(xmppHost, xmppPort);
//connConfig.setSecurityMode(SecurityMode.disabled);
connConfig.setSecurityMode(SecurityMode.required);
connConfig.setSASLAuthenticationEnabled(false);
connConfig.setCompressionEnabled(false);
try {
XMPPConnection xc = new XMPPConnection(connConfig);
xc.connect(); // 建立和server端的额连接
xmppManager.setConnection(xc);
// namespace为androidpn:iq:notification
ProviderManager.getInstance().addIQProvider("notification",
"androidpn:iq:notification",new NotificationIQProvider());
} catch (XMPPException e) {
e.printStackTrace();
}
}else{
}
}
}*/
private boolean isConnect(){
return connection !=null && connection.isConnected();
}
public void setConnection(XMPPConnection connection) {
this.connection = connection;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public String getXmppHost() {
return xmppHost;
}
public void setXmppHost(String xmppHost) {
this.xmppHost = xmppHost;
}
public int getPort() {
return xmppPort;
}
}