一、下載DDPush的jar包並導入到Java項目
二、編寫推送代碼
Pusher pusher = null;
try {
//三個參數分別對應:DDPush服務器IP,DDPush默認推送端口,響應超時
pusher = new Pusher("192.168.X.X", 9999, 5000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = "";
Scanner scanner = null;
while (!str.equals("bye")) {
System.out.println("請輸入要發送的消息:");
scanner = new Scanner(System.in);
str = scanner.next();
System.out.println("你輸入的是:"+str);
boolean flag = false;
try {
//user1表示要推到的用戶,轉換爲DDPush的uuid
flag = pusher.push0x20Message(StringUtil.md5Byte("user1"), str.getBytes("UTF-8"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}
System.out.println(flag);
}
三、編寫接收推送的代碼
1)編寫自定義的TCPClient
public class MyTCPClient extends TCPClientBase{
public MyTCPClient(byte[] uuid) throws Exception {
//uuid, appid, DDPush服務器IP,DDPush默認接收消息的端口,響應超時
super(uuid, 1, "192.168.X.X", 9966, 5);
}
@Override
public boolean hasNetworkConnection() {
// TODO Auto-generated method stub
return true;
}
@Override
public void onPushMessage(Message msg) {
// TODO Auto-generated method stub
if (msg == null) {
System.out.println("msg is null");
return;
}
if (msg.getData() == null || msg.getData().length == 0) {
System.out.println("msg has no data");
return;
}
String str = null;
try {
str = new String(msg.getData(),5,msg.getContentLength(), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
str = "Exception";
}
System.out.println(str);
}
@Override
public void trySystemSleep() {
// TODO Auto-generated method stub
}
}
2)調用MyTCPClient
MyTCPClient mClient = null;
mClient = new MyTCPClient(StringUtil.md5Byte("user2"));//user2接收消息的用戶
mClient.setHeartbeatInterval(60);
mClient.start();
四、啓動DDPush服務端
通過dos命令啓動DDPush服務
> start.bat
五、啓動客戶端程序就可以發送消息了