package im;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;
/*
* 即时消息发送类
*/
public class JstxInit
{
private static String ip = "127.0.0.1";//openfire服务器地址
private static String username = "server";//openfire设置的用户
private static String password = "123456";
private static String appRes = "Smack";//Smack或Spark都可
private static XMPPConnection con;
public JstxInit()
{
}
/**
* 进行信息发送
* 注意:批量发送消息时,存在丢失前几条的问题!
* @param receiveUser 接收者
* @param content 发送的内容
* @return 返回发送是否成功标志,1表示成功,2表示失败
*/
public static synchronized String sendMsg(String receiveUser, String content)
{
System.out.println(content+"~start~");
String flag = "1";
try
{
Message message = new Message();
Chat chat = con.getChatManager().createChat(receiveUser,new MessageListenerImpl());
message.setBody(content);
chat.sendMessage(message);
}
catch (Exception e)
{
String msg = "发送给用户 " + receiveUser +
"content is " +
content + "isfailed:" +
e.toString();
System.out.println(msg);
flag = "2";
}
try {
new Thread().sleep(100L);
} catch (InterruptedException e1) {}
System.out.println(content+"~end~");
return flag;
}
/*
* 获取回话连接连接
* 如果存在,则直接返回当前回话;
* 如果 不存在,则需要进行回话建立
*/
public static XMPPConnection getConnection()
{
//如果不为NULL直接返回
if(con != null)
{
return con;
}else
{
//创建回话连接
boolean bflag = true;
int count = 2;//最多连接COUNT次数后,如果失败则返回NULL
while (bflag)
{
if(count == 0)
{
break;
}
try
{
//开始建立回话连接
con = new XMPPConnection(JstxInit.ip);
con.connect();
con.login(JstxInit.username, JstxInit.password, JstxInit.appRes);
//如果建立成功,则循环标志为false
if(con != null)
{
bflag = false;
System.out.println("Success:即时通讯登录成功!【" + JstxInit.username + "&" + JstxInit.password + "】");
}else
{
System.out.println("Failed:即时通讯登录失败!【" + JstxInit.username + "&" + JstxInit.password + "】");
//如果建立失败,等待5秒后进行重新连接
new Thread().sleep(5000L);
}
} catch (Exception e)
{
System.out.println("Failed:即时通讯登录失败!【" + JstxInit.username + "&" + JstxInit.password + "】");
//如果建立失败,等待5秒后进行重新连接
try {
new Thread().sleep(5000L);
} catch (InterruptedException e1) {}
count--;
}
}
}
return con;
}
public static void main(String[] args)
{
if(JstxInit.getConnection()!=null)
{
for(int n=0 ; n < 5 ; n++)
{
JstxInit.sendMsg("test1@127.0.0.1/Spark", "测试A"+n);
}
}
}
}
- 1
- 2
- 3
前往页