当前位置: 首页 > 工具软件 > xmpp-go > 使用案例 >

XMPP-SMACK-TEST

程正阳
2023-12-01




package com.ccdt.test1;

import java.util.Scanner;

import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Registration;

public class XmppTest_sender {
    static private XMPPConnection connect;
    static private XMPPConnection connect2;
    static private AccountManager accountManager;
    
	static String ip = "112.74.83.206";
    static int port = 5222;
    static String domain=ip;
    static String name1 = "stivenjin";
    static String name2 = "stivenjin002";
    static String pwd = "123456";
    
    private static class ResData {
        @SuppressWarnings("unused")
        public String resCode = "";
        @SuppressWarnings("unused")
        public String resDesc = "";
    }
    /**
     * @param args
     */
    public static void main(String[] args) {

        boolean isRegister = false;
        
        //1 connect to server
        SmackConfiguration.setPacketReplyTimeout(15*1000);
        connect2 = getConnection(ip,port,domain);
        System.out.println("get connection2 = " + connect2);
        if (connect2 == null) return;
        try {
            connect2.connect();//开启链接
            accountManager = connect2.getAccountManager();// 获取账户管理类
        } catch (XMPPException e) {
            e.printStackTrace();
        }
        System.out.println("connection ok!");
        
        //3.login
        login(connect2,name2,pwd);
        
        //4.send chat
        boolean t = true;
        int idx = 0;
        while (t) {
            System.out.println("read chat..");
            Scanner input = new Scanner(System.in);
            String msg = input.nextLine();
			System.out.println("before sendMessages!!");
			sendMessages(connect2,name1,msg+":client send!!");
			
			sendBroadcast("通知标题xx","通知内容xxxx");
        }
        
        logout(connect);
        try {
            System.out.println("watting for close..");
            Thread.sleep(5000);
            System.out.println("altready close..");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logout(connect2);
    }
    
    public static XMPPConnection getConnection(String ip,int port,String domain) {
        System.out.println("getConnection ip=" + ip + ",port="+port+",domain="+domain);
        ConnectionConfiguration config = new ConnectionConfiguration(ip,port,domain);
        config.setReconnectionAllowed(true);// 允许自动连接
        config.setSendPresence(true);//在线
        XMPPConnection connect = new XMPPConnection(config);
        return connect;
    }
    
    public static ResData rejister(XMPPConnection conn,String uName,String pwd) {
        Registration reg = new Registration();
        reg.setType(IQ.Type.SET);
        reg.setUsername(uName);// 注意这里createAccount注册时,参数是username,不是jid,是“@”前面的部分。
        reg.setPassword(pwd);
        reg.setInstructions("instruction");
        reg.addAttribute("android", "geolo_createUser_android");// 这边addAttribute不能为空,否则出错。所以做个标志是android手机创建的吧!!!!!
        PacketFilter filter = new AndFilter(new PacketIDFilter(
                reg.getPacketID()), new PacketTypeFilter(IQ.class));
        PacketCollector collector = connect.createPacketCollector(filter);
        conn.sendPacket(reg);
        IQ result = (IQ) collector.nextResult(SmackConfiguration
                .getPacketReplyTimeout());
        // Stop queuing results
        collector.cancel();// 停止请求results(是否成功的结果)
        ResData res = new ResData();
        if (result == null) {
            System.out.println("err result null!");
        } else {
            res.resCode = result.getType().toString();
            if (result.getType() == IQ.Type.ERROR) {
                res.resDesc = result.getError().toString();
                if (res.resDesc.equalsIgnoreCase("conflict(409)")) {
                    System.out.println("err:" + res.resDesc);
                }
            } else if (result.getType() == IQ.Type.RESULT) {
                System.out.println(" result success!");
            }
        } 
        return res;
    }
    
    public static ResData login(XMPPConnection connect,String uName,String pwd) {
        ResData res = new ResData();
        // 登录
        try {
            connect.login(uName, pwd,"res_"+uName);
            connect.sendPacket(new Presence(Presence.Type.available));
            System.out.println("login user:"+connect.getUser()); 
        } catch (XMPPException e) {
            e.printStackTrace();
        }
        return res;
    }
    
    public static ResData logout(XMPPConnection connect) {
        ResData res = new ResData();
        // 退出
        System.out.println("logout user:"+connect.getUser()); 
        Presence presence = new Presence(Presence.Type.unavailable);   //这里如果改成unavailable则会显示用户不在线
        connect.disconnect(presence);
        return res;
    }
    
    public static ResData updateStatus(XMPPConnection connect,String status) {
        ResData res = new ResData();
        //更改用户状态代码:
        Presence presence = new Presence(Presence.Type.available);   //这里如果改成unavailable则会显示用户不在线
        presence.setStatus("Go fishing");
        connect.sendPacket(presence);
        connect.getRoster();
        System.out.println("updateStatus over!");
        return res;
    }
    
    /**
     * TODO FIXME! 为实现功能!!!!
     * @param subject
     * @param msg
     * @return
     */
    public static ResData sendBroadcast(String subject,String msg) {
        ResData res = new ResData();
       XMPPConnection con = getConnection(ip,port,domain);
        try {
        	con.connect();
        	con.login("admin", "openfire452196738","SmackTest3");
        } catch (XMPPException e) {
            e.printStackTrace();
        } 
        Message newmsg = new Message(); 
        newmsg.setTo(name1+"@"+domain);
        newmsg.setSubject(subject);
        newmsg.setBody(msg);
        newmsg.setType(Message.Type.headline);// normal支持离线 
        con.sendPacket(newmsg);
        System.out.println("sendBroadcast over!");
        con.disconnect();
        return res;
    }
    
    /**
     * 发送消息
     * @param con 用户连接对象
     * @param user 用户JID
     * @param msg 发送内容
     */
    public static synchronized void sendMessages(XMPPConnection con, String user, String msg) {
        if (null != user && !"@".equals(user)) {
            user = user + "@" + con.getServiceName();
        }
        Chat chat = con.getChatManager().createChat(user, null);
        try {
            chat.sendMessage(msg);
        } catch (XMPPException e) {
            e.printStackTrace();
        }
    }
}




package com.ccdt.test1;

import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Registration;

public class XmppTest {
    static private XMPPConnection connect;
    static private XMPPConnection connect2;
    static private AccountManager accountManager;
    
    private static class ResData {
        @SuppressWarnings("unused")
        public String resCode = "";
        @SuppressWarnings("unused")
        public String resDesc = "";
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        String ip = "112.74.83.206";
        int port = 5222;
        String domain=ip;
        String name1 = "stivenjin";
        String name2 = "stivenjin002";
        String pwd = "123456";
        boolean isRegister = false;
        
        //1 connect to server
        SmackConfiguration.setPacketReplyTimeout(15*1000);
        connect = getConnection(ip,port,domain);
        System.out.println("get connection = " + connect);
        if (connect == null) return;
        try {
            connect.connect();//开启链接
            accountManager = connect.getAccountManager();// 获取账户管理类
        } catch (XMPPException e) {
            e.printStackTrace();
        }
        System.out.println("connection ok!");
        
        //2.rejister
        if (isRegister) {// 是否先注册
            ResData data = rejister(connect,name1,pwd);
            if (data.resCode.equals(IQ.Type.ERROR.toString())) {
                System.out.println("rejister err:"+data.resDesc);
            }
        }
        
        //3.login
        login(connect,name1,pwd);
        
        //================ 收离线消息 =======================//
        // User2 checks the number of offline messages
        /*OfflineMessageManager offlineManager = new OfflineMessageManager(connect);
        java.util.Iterator<OfflineMessageHeader> headers = null;
        try {
            System.out.println("Wrong number of offline messages "+ offlineManager.getMessageCount());
            // Check the message headers
            headers = offlineManager.getHeaders();
        } catch (XMPPException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
       
        System.out.println("No message header was found"+headers.hasNext());
        List<String> stamps = new ArrayList<String>();
        while (headers.hasNext()) {
            OfflineMessageHeader header = (OfflineMessageHeader) headers.next();
            System.out.println("No stamp was found in the message header"+header.getStamp());
            stamps.add(header.getStamp());
        }
        System.out.println("Wrong number of headers"+2+ stamps.size());
        // Get the offline messages
        java.util.Iterator<Message> messages = null;
        try {
            messages = offlineManager.getMessages(stamps);
        } catch (XMPPException e1) {
            e1.printStackTrace();
        }
        System.out.println("No message was found"+ messages.hasNext());
        stamps = new ArrayList<String>();
        while (messages.hasNext()) {
            Message message = (Message) messages.next();
            System.out.println("@@@@@@@@@@@@@ offline msg = "+message.getBody());
            OfflineMessageInfo info = (OfflineMessageInfo) message.getExtension("offline",
                    "http://jabber.org/protocol/offline");
            System.out.println("No offline information was included in the offline message"+ info);
            System.out.println("No stamp was found in the message header"+ info.getNode());
            stamps.add(info.getNode());
        }
        
        Presence presence = new Presence(Presence.Type.available);
        connect.sendPacket(presence);//上线了
        */
        
        ChatManager chatmanager = connect.getChatManager();
        chatmanager.addChatListener(new ChatManagerListener() {
            public void chatCreated(Chat chat, boolean arg1) {
                chat.addMessageListener(new MessageListener() {
                    public void processMessage(Chat arg0, Message message) {
                        // 若是聊天窗口已存在,将消息转往目前窗口 //若是窗口不存在,开新的窗口并注册
                        System.out.println("收到消息f:" + message.getFrom());
                        System.out.println("收到消息t:" + message.getTo());
                        System.out.println("收到消息c:" + message.getBody());
                    }
                });
            }
        });
        
        connect.addPacketListener(new PacketListener() {
            public void processPacket(Packet packet) {
                Message message = (Message) packet;
                System.out.println("收到消息ff:" + message.getFrom());
                System.out.println("收到消息tt:" + message.getTo());
                System.out.println("收到消息cc:" + message.getBody());
            }
        }, new PacketTypeFilter(Message.class));
        
        //4.chat
        System.out.println("befor chat..");
        
        boolean t = true;
        int idx = 0;
        
        
        try {
            sendBroadcast(ip,port,domain);
            System.out.println("watting for logout..");
            Thread.sleep(1160000);
            System.out.println("watting for logout..");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        
        logout(connect);
        try {
            System.out.println("watting for close..");
            Thread.sleep(11115000);
            System.out.println("altready close..");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public static XMPPConnection getConnection(String ip,int port,String domain) {
        System.out.println("getConnection ip=" + ip + ",port="+port+",domain="+domain);
        ConnectionConfiguration config = new ConnectionConfiguration(ip,port,domain);
        config.setReconnectionAllowed(true);// 允许自动连接
        config.setSendPresence(false);//先不告诉在线,方便取离线消息
        XMPPConnection connect = new XMPPConnection(config);
        return connect;
    }
    
    public static ResData rejister(XMPPConnection conn,String uName,String pwd) {
        Registration reg = new Registration();
        reg.setType(IQ.Type.SET);
        reg.setUsername(uName);// 注意这里createAccount注册时,参数是username,不是jid,是“@”前面的部分。
        reg.setPassword(pwd);
        reg.setInstructions("instruction");
        reg.addAttribute("android", "geolo_createUser_android");// 这边addAttribute不能为空,否则出错。所以做个标志是android手机创建的吧!!!!!
        PacketFilter filter = new AndFilter(new PacketIDFilter(
                reg.getPacketID()), new PacketTypeFilter(IQ.class));
        PacketCollector collector = connect.createPacketCollector(filter);
        conn.sendPacket(reg);
        IQ result = (IQ) collector.nextResult(SmackConfiguration
                .getPacketReplyTimeout());
        // Stop queuing results
        collector.cancel();// 停止请求results(是否成功的结果)
        ResData res = new ResData();
        if (result == null) {
            System.out.println("err result null!");
        } else {
            res.resCode = result.getType().toString();
            if (result.getType() == IQ.Type.ERROR) {
                res.resDesc = result.getError().toString();
                if (res.resDesc.equalsIgnoreCase("conflict(409)")) {
                    System.out.println("err:" + res.resDesc);
                }
            } else if (result.getType() == IQ.Type.RESULT) {
                System.out.println(" result success!");
            }
        } 
        return res;
    }
    
    public static ResData login(XMPPConnection connect,String uName,String pwd) {
        ResData res = new ResData();
        // 登录
        try {
            connect.login(uName, pwd,"res_"+uName);
            connect.sendPacket(new Presence(Presence.Type.available));
            System.out.println("login user:"+connect.getUser()); 
        } catch (XMPPException e) {
            e.printStackTrace();
        }
        return res;
    }
    
    public static ResData logout(XMPPConnection connect) {
        ResData res = new ResData();
        // 退出
        System.out.println("logout user:"+connect.getUser()); 
        Presence presence = new Presence(Presence.Type.unavailable);   //这里如果改成unavailable则会显示用户不在线
        connect.disconnect(presence);
        return res;
    }
    
    public static ResData chat(XMPPConnection connect, String toUserName,
            String toIpOrDomain, String msg) {
        ResData res = new ResData();
        if (connect != null)
            try {
                connect.getChatManager()
                        .createChat(toUserName + "@" + toIpOrDomain, null)
                        .sendMessage(msg);
            } catch (XMPPException e) {
                e.printStackTrace();
            }
        return res;
    }
    
    public static ResData updateStatus(XMPPConnection connect,String status) {
        ResData res = new ResData();
        //更改用户状态代码:
        Presence presence = new Presence(Presence.Type.available);   //这里如果改成unavailable则会显示用户不在线
        presence.setStatus("Go fishing");
        connect.sendPacket(presence);
        connect.getRoster();
        System.out.println("updateStatus over!");
        return res;
    }
    
    public static ResData sendBroadcast(String ip,int port,String domain) {
        ResData res = new ResData();
        final ConnectionConfiguration connectionConfig = new ConnectionConfiguration(
                ip, port, domain);

        // 允许自动连接
        connectionConfig.setReconnectionAllowed(true);
        connectionConfig.setSendPresence(true);

        Connection connection = new XMPPConnection(connectionConfig);
        try {
            connection.connect();// 开启连接
        } catch (XMPPException e) {
            throw new IllegalStateException(e);
        }
        try {
            connection.login("admin", "openfire452196738","SmackTest3");
        } catch (XMPPException e) {
            e.printStackTrace();
        } 
        Message newmsg = new Message(); 
        //newmsg.setTo("");
        newmsg.setSubject("重要通知");
        newmsg.setBody("今天下午2点60分有会!");
        newmsg.setType(Message.Type.headline);// normal支持离线 
        connection.sendPacket(newmsg);
        connection.disconnect();
        return res;
    }
    
    /**
     * 发送消息
     * 
     * @param con
     *            用户连接对象
     * @param user
     *            用户JID
     * @param msg
     *            发送内容
     */
    public synchronized void sendMessages(XMPPConnection con, String user, String msg) {
        if (null != user && !"@".equals(user)) {
            user = user + "@" + con.getServiceName();
        }
        Chat chat = con.getChatManager().createChat(user, null);
        try {
            chat.sendMessage(msg);
        } catch (XMPPException e) {
            e.printStackTrace();
        }
    }
}



 类似资料: