java 代码模拟androidpn消息推送客户端(测试)

来源:互联网 发布:linux脚本怎么开机自启 编辑:程序博客网 时间:2024/05/26 17:44

模拟手机端接受推送消息和连接服务器,用于测试anroidpn服务器

目录结构如下:


Clienttest.java

package client;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.PacketCollector;
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.Presence;
import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smack.provider.ProviderManager;

public class Clienttest  extends Thread{
    
    protected final Log log = LogFactory.getLog(getClass());
    
    public String name;
    
    public  void setNames(String name) {
        this.name = name;
    }
    public int index;
    
    

    public void setIndex(int index) {
        this.index = index;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        Clienttest client = new Clienttest();
        XMPPConnection connection=   client.conServer();
        String result=client.regist(connection,"sssssd"+index, "123");
        System.out.println("第 "+ index +"个  regist result is----> "+result);
        client.login(index,connection,"sssssd"+index, "123");
        
        new CThread(connection).start();    
        System.out.println("----");
        log.info("----------------------------------------------------------->");
    }
    
    public  XMPPConnection conServer() {
        ConnectionConfiguration config = new ConnectionConfiguration(
                "192.168.1.59", 5222);//修改为需要连接的ip地址
        config.setSecurityMode(SecurityMode.required);
        config.setSASLAuthenticationEnabled(false);
        config.setCompressionEnabled(false);

        /** 创建connection链接 */
        try {
            XMPPConnection    connection = new XMPPConnection(config);
            connection.connect();
             ProviderManager.getInstance().addIQProvider("notification",
                     "androidpn:iq:notification",
                     new NotificationIQProvider());
            return connection;
        } catch (XMPPException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String newRandomUUID() {
        String uuidRaw = UUID.randomUUID().toString();
        return uuidRaw.replaceAll("-", "");
    }

    public String regist(XMPPConnection connection,String username, String password) {
        if (connection == null)
            return "0";

        Registration reg = new Registration();
        reg.setType(IQ.Type.SET);
        reg.setTo(connection.getServiceName());

        Map<String, String> user = new HashMap<String, String>();
        user.put("username", username);
        user.put("password", password);
        user.put("email", "865227514@qq.com");
        user.put("name", "larena");
        reg.setAttributes(user);
        PacketFilter filter = new AndFilter(new PacketIDFilter(
                reg.getPacketID()), new PacketTypeFilter(IQ.class));
        PacketCollector collector = connection.createPacketCollector(filter);
        connection.sendPacket(reg);
        IQ result = (IQ) collector.nextResult(SmackConfiguration
                .getPacketReplyTimeout());
        // Stop queuing results
        //collector.cancel();// 停止请求results(是否成功的结果)
        if (result == null) {
            System.out.println("No response from server.");
            return "0";
        } else if (result.getType() == IQ.Type.RESULT) {
            return "1";
        } else { // if (result.getType() == IQ.Type.ERROR)
            if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
                System.out.println("IQ.Type.ERROR: "
                        + result.getError().toString());
                return "2";
            } else {
                System.out.println("IQ.Type.ERROR: "
                        + result.getError().toString());
                return "3";
            }
        }
    }

    public boolean login(int i,XMPPConnection connection,String username, String password) {
        System.out.println("try to login...");
        log.debug("try to login...");
        try {
            if (connection != null)
            {
                connection.login(username, password,"AndroidpnClient");
                   PacketFilter packetFilter = new PacketTypeFilter(
                           NotificationIQ.class);
                connection.addPacketListener(new NotificationPacketListener(i), packetFilter);
                System.out.println("Login successfully!");                
                return true;
            }            

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Login failed!");
        }
        return false;
    }
    
//    public static void main(String[] args) {
//        
//        for(int i=0;i<500;i++){
//            Clienttest client = new Clienttest();
//            XMPPConnection connection=   client.conServer();
//            String result=client.regist(connection,"sssss"+i, "123");
//            System.out.println("第 "+  i+"个  regist result is----> "+result);
//            client.login(i,connection,"sssss"+i, "123");
//            
//            new CThread(connection).start();    
//            System.out.println("----");
//        }
//        
//        
//    }
    static class CThread extends Thread{
        XMPPConnection connection;
        
        public CThread(XMPPConnection connection) {
            super();
            this.connection = connection;
        }

        @Override
        public void run() {
            Presence p=new Presence(Presence.Type.available);
            while(true){
                connection.sendPacket(p);
                try {
                    sleep(5000);
                } catch (InterruptedException e) {
                    
                    e.printStackTrace();
                }
            }
        }
        
    }
}



NotificationIQ.java

/*
 * Copyright (C) 2010 Moduad Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package client;

import org.jivesoftware.smack.packet.IQ;

/**
 *
 * @author xu duzhou
 *
 */
public class NotificationIQ extends IQ {

    private String id;

    private String apiKey;

    private String title;

    private String message;

    private String uri;

    public NotificationIQ() {
    }

    @Override
    public String getChildElementXML() {
        StringBuilder buf = new StringBuilder();
        buf.append("<").append("notification").append(" xmlns=\"").append(
                "androidpn:iq:notification").append("\">");
        if (id != null) {
            buf.append("<id>").append(id).append("</id>");
        }
        buf.append("</").append("notification").append("> ");
        return buf.toString();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getApiKey() {
        return apiKey;
    }

    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String url) {
        this.uri = url;
    }

}



NotificationIQProvider.java

/*
 * Copyright (C) 2010 Moduad Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package client;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.provider.IQProvider;
import org.xmlpull.v1.XmlPullParser;

/**
 * This class parses incoming IQ packets to NotificationIQ objects.
 *
 */
public class NotificationIQProvider implements IQProvider {

    public NotificationIQProvider() {
    }

    public IQ parseIQ(XmlPullParser parser) throws Exception {

        NotificationIQ notification = new NotificationIQ();
        for (boolean done = false; !done;) {
            int eventType = parser.next();
            if (eventType == 2) {
                if ("id".equals(parser.getName())) {
                    notification.setId(parser.nextText());
                }
                if ("apiKey".equals(parser.getName())) {
                    notification.setApiKey(parser.nextText());
                }
                if ("title".equals(parser.getName())) {
                    notification.setTitle(parser.nextText());
                }
                if ("message".equals(parser.getName())) {
                    notification.setMessage(parser.nextText());
                }
                if ("uri".equals(parser.getName())) {
                    notification.setUri(parser.nextText());
                }
            } else if (eventType == 3
                    && "notification".equals(parser.getName())) {
                done = true;
            }
        }

        return notification;
    }

}



NotificationPacketListener.java

/*
 * Copyright (C) 2010 Moduad Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package client;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Packet;

//import android.content.Intent;

/**
 * This class notifies the receiver of incoming notifcation packets asynchronously.  
 *
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class NotificationPacketListener implements PacketListener {

    protected final Log log = LogFactory.getLog(getClass());
    
    int num;

    public NotificationPacketListener(int i) {
        num=i;
    }

    public void processPacket(Packet packet) {
        log.debug(num+"信息收到了。。。。。。。。。。。。。。。。");
        System.out.println(num+"信息收到了。。。。。。。。。。。。。。。。");
        if (packet instanceof NotificationIQ) {
            NotificationIQ notification = (NotificationIQ) packet;

            if (notification.getChildElementXML().contains(
                    "androidpn:iq:notification")) {
                String notificationId = notification.getId();
                String notificationApiKey = notification.getApiKey();
                String notificationTitle = notification.getTitle();
                String notificationMessage = notification.getMessage();
                //                String notificationTicker = notification.getTicker();
                String notificationUri = notification.getUri();
//                System.out.println("鏀跺埌娑堟伅");
//                Intent intent = new Intent(Constants.ACTION_SHOW_NOTIFICATION);
//                intent.putExtra(Constants.NOTIFICATION_ID, notificationId);
//                intent.putExtra(Constants.NOTIFICATION_API_KEY,
//                        notificationApiKey);
//                intent
//                        .putExtra(Constants.NOTIFICATION_TITLE,
//                                notificationTitle);
//                intent.putExtra(Constants.NOTIFICATION_MESSAGE,
//                        notificationMessage);
//                intent.putExtra(Constants.NOTIFICATION_URI, notificationUri);
//                //                intent.setData(Uri.parse((new StringBuilder(
//                //                        "notif://notification.androidpn.org/")).append(
//                //                        notificationApiKey).append("/").append(
//                //                        System.currentTimeMillis()).toString()));
//
//                xmppManager.getContext().sendBroadcast(intent);
            }
        }

    }

}


PersistentConnectionListener.java

/*
 * Copyright (C) 2010 Moduad Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package client;

import org.jivesoftware.smack.ConnectionListener;


/**
 * A listener class for monitoring connection closing and reconnection events.
 *
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class PersistentConnectionListener implements ConnectionListener {


    public PersistentConnectionListener() {
    }

    public void connectionClosed() {
    }

    public void connectionClosedOnError(Exception e) {
       
       
    }

    public void reconnectingIn(int seconds) {
    }

    public void reconnectionFailed(Exception e) {
    }

    public void reconnectionSuccessful() {
    }

}

Test.java

package client;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Test {
    
    
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
        for(int i=11;i<20;i++){
            
            Clienttest thread = new Clienttest();
            thread.setNames(System.currentTimeMillis()+""+i);
            thread.setIndex(i);
            thread.start();
            
        }
        
    }

}


源码下载:模拟androidpn-client

0 0
原创粉丝点击