天天看点

使用smack基于xmpp服务实现即时通讯

由于平台中礼物系统需要一个后台主动的广播,之前基于Strophe.js的前端客户端无法满足需要,故添加了smack(一个开源,易于使用的XMPP(jabber)客户端类库。)
           

pom依赖

<!-- im相关 -->
            <dependency>
                <groupId>org.igniterealtime.smack</groupId>
                <artifactId>smack-java7</artifactId>
                <version>4.1.1</version>
            </dependency>
            <dependency>
                <groupId>org.igniterealtime.smack</groupId>
                <artifactId>smack-tcp</artifactId>
                <version>4.1.1</version>
            </dependency>
            <dependency>
                <groupId>org.igniterealtime.smack</groupId>
                <artifactId>smack-im</artifactId>
                <version>4.1.1</version>
            </dependency>
            <dependency>
                <groupId>org.igniterealtime.smack</groupId>
                <artifactId>smack-extensions</artifactId>
                <version>4.1.1</version>
            </dependency>
            <!-- im相关 -->
           

java代码(xmpp服务连接登录及加入聊天室发消息)

import java.io.IOException;
import java.util.UUID;

import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatManager;

/** 
 * ClassName: Broadcast.java <br>
 * Description: 送礼物IM系统广播工具类<br>
 * Create by: name:yuxin <br>email: [email protected] <br>
 * Create Time: 2017年8月24日<br>
 */
public class Broadcast {

    private  String host = "47.92.39.22";
    private  int port = ;
    private  String account = "[email protected]";
    private  String password = "system-prod-mobile";

    public static void main(String[] args) throws XMPPException,
            SmackException, IOException, InterruptedException {
        int i=;
        Broadcast broadcast = new Broadcast();
        String roomId = "yyyuuu";
        String body = "送你一把加特林---哒哒哒哒哒!!!!!";
        while(i<){
            broadcast.loginAndSend(roomId,body);
            i++;
        }
    }

    public  void loginAndSend(String roomId, String body) throws XMPPException, SmackException, IOException{

        //新启线程
//      new Thread(new Runnable() {
//          @Override
//          public void run() {
                XMPPTCPConnection xc = null;
                try {
                    long current = System.currentTimeMillis();
                    xc = login(xc);
                    MultiUserChatManager mMultiUserChatManager = MultiUserChatManager.getInstanceFor(xc);
                    //计时
                    joinRoomAndSend(mMultiUserChatManager,roomId,body);
                    //处理订单业务
                    System.out.println((System.currentTimeMillis() - current) + "毫秒");
                    //为购买用户发送购买成功的消息通知
                    xc.instantShutdown();
                    System.out.println(body);
                } catch (Exception e) {
                    if(xc!=null)xc.instantShutdown();
                    e.printStackTrace();
                }
//          }

//      }).start();
    }

    public XMPPTCPConnection login(XMPPTCPConnection connection) throws XMPPException, SmackException, IOException{
        SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
        SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
        connection = getConnection(connection);
        connection.login();
        return connection;
    }

    /**
     * 获得与服务器的连接 config.setSASLAuthenticationEnabled(false);
     * 
     * @return
     */
    public  XMPPTCPConnection getConnection(XMPPTCPConnection connection) {
        try {
            if (connection == null) {
                XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration
                        .builder()
                        // 服务器IP地址
                        .setHost(host)
                        // 服务器端口
                        .setPort(port)
                        // 服务器名称(管理界面的 主机名)
                        .setServiceName(host)
                        // 是否开启安全模式
                        .setSecurityMode(
                                XMPPTCPConnectionConfiguration.SecurityMode.disabled)
                        // .set
                        // 是否开启压缩
                        .setCompressionEnabled(false).setResource(UUID.randomUUID().toString().replaceAll("-", ""))
                        .setUsernameAndPassword(account,password)
                        // 开启调试模式
                        .setDebuggerEnabled(false).build();
                connection = new XMPPTCPConnection(config);
                connection.connect();
            }
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public  void joinRoomAndSend(MultiUserChatManager mMultiUserChatManager,String roomId,String body){
        try {
            MultiUserChat multiUserChat=mMultiUserChatManager.getMultiUserChat(roomId+"[email protected]");
            multiUserChat.join("system");
            Message message=multiUserChat.createMessage();
            message.setBody(body);
            multiUserChat.sendMessage(message);
        } catch (NoResponseException e) {
            e.printStackTrace();
        } catch (XMPPErrorException e) {
            e.printStackTrace();
        } catch (NotConnectedException e) {
            e.printStackTrace();
        }
    }
}