Hey how can i display every response from the xmpp server?
I try to send messages but a lot of them get lost on the way so i want to check the response of the server. I am using smack 3.3.1 sending to the facebook xmpp port.
DeliveryReceiptManager and/or MessageEventManager wont show anything so i would like to see everything the server is responding!
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com",5222);
config.setSASLAuthenticationEnabled(true);
XMPPConnection connection = new XMPPConnection(config);
try {
//ESTA LINEA HACE QUE NO DE TIMEOUT
SmackConfiguration.setPacketReplyTimeout(15000);
XMPPConnection.DEBUG_ENABLED = true;
SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM", SASLXFacebookPlatformMechanism.class);
SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
connection.connect();
String apiKey = "1234567";
String accessToken = "";
connection.login(apiKey, accessToken);
}catch (XMPPException e){
e.printStackTrace();
}
try {
DeliveryReceiptManager deliveryReceiptManager = DeliveryReceiptManager.getInstanceFor(connection);
deliveryReceiptManager.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(String s, String s2, String s3) {
System.out.println("REVEIVED RESPONCE");
System.out.println(s);
System.out.println(s2);
System.out.println(s3);
}
});
Chat chat = connection.getChatManager().createChat("1234567890#chat.facebook.com", new MessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
if(message.getType() == Message.Type.chat)
System.out.println(chat.getParticipant() + " says: " + message.getBody());
}
});
Message msg = new Message();
msg.setSubject("Invite");
msg.setBody("blablabla");
DeliveryReceiptManager.addDeliveryReceiptRequest(msg);
//MessageEventManager.addNotificationsRequests(msg, true, true, true, true);
chat.sendMessage(msg);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}catch (XMPPException e){
e.printStackTrace();
}
try {
Thread.sleep(10000);
}catch (InterruptedException e) {
e.printStackTrace();
}
Connection.DEBUG_ENABLED = true;
Related
I am new to signalR, tried to connect to a hub and got a connectionId after successful connection.
my code
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String host = "url";
HubConnection connection = new HubConnection(host);
HubProxy hub = connection.createHubProxy("pttdashboardhub");
ClientTransport clientTransport = new ServerSentEventsTransport(connection.getLogger());
SignalRFuture<Void> signalRFuture = connection.start(clientTransport);
try {
signalRFuture.get();
System.out.println(connection.getConnectionId());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
hub.on("onEvent",
new SubscriptionHandler1<String>() {
#Override
public void run(String s) {
System.out.println("================ "+s);
}
}, String.class);
server code
var eventHub = GlobalHost.ConnectionManager.GetHubContext<EventHub>();
var result = eventHub.Clients.Group("pttdashboard").onEvent(data);
the problem comes when hub.on function executes i get nothing from the server.
Any help is appreciated.
You can use subscribe function instead of on function.
hub.subscribe("onEvent").addReceivedHandler(new Action<JsonElement[]>(){
#Override
public void run(JsonElement obj) {
System.out.println("================ "+s);
}
});
I hope this helps you.
I have created a client and a server, which both work fine and have no trouble connecting. Now I would like to be able to connect from my android phone to the server. I have imported the kryonet library and copy-pasted the client code into a new android project. The code gave me some errors, but I fixed those. When I tried testing my app, it didn't give me any errors, but my server wasn't getting any connections either. I looked a bit in the LogCat logs, and found out it keeps sticking at "Connecting..". I am totally stuck. This is my android code:
public void openSocket(View view){
Log.i(TAG, "test1");
EditText portText= (EditText)findViewById(R.id.port);
String parts[] = portText.getText().toString().split(":");
partIP = parts[0];
String partPort = parts[1];
port = Integer.parseInt(partPort);
try {
client = new Client();
client.start();
register();
pHandler = new PacketHandler();
connect();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void register() {
client.getKryo().register(Packet.class);
client.getKryo().register(Packet1Connected.class);
client.getKryo().register(String.class);
client.getKryo().register(String[].class);
client.getKryo().register(Object[].class);
}
public static void connect() {
try {
String IP = "*MY IP*:25565";
String[] Ip = IP.split(":");
String ipFinal = Ip[0];
int port = Integer.parseInt(Ip[1]);
client.connect(5000, ipFinal, port, port);
} catch (IOException e) {
try {
Thread.sleep(15000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
System.out.println("Trying to connect.");
connect();
}
Packet1Connected packet = new Packet1Connected();
packet.id = "Android";
client.sendTCP(packet);
}
And this is my normal client code:
public static void main(String[] args) {
try {
client = new Client();
client.start();
register();
pHandler = new PacketHandler();
new Main();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void register() {
client.getKryo().register(Packet.class);
client.getKryo().register(Packet1Connected.class);
client.getKryo().register(String.class);
client.getKryo().register(String[].class);
client.getKryo().register(Object[].class);
}
public Main() {
try {
connect();
Thread t = new Thread(this);
t.start();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void connect() {
try {
String IP = "*MY IP*:25565";
String[] Ip = IP.split(":");
String ipFinal = Ip[0];
int port = Integer.parseInt(Ip[1]);
client.connect(5000, ipFinal, port, port);
} catch (IOException e) {
try {
Thread.sleep(15000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
System.out.println("Trying to connect.");
connect();
}
Packet1Connected packet = new Packet1Connected();
packet.id = System.getProperty("user.name");
client.sendTCP(packet);
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(3000);
if (!client.isConnected())
connect();
} catch (InterruptedException e) {
pHandler.checkException(e);
}
}
}
}
So this:
client.connect(5000, ipFinal, port, port);
is the line it gets stuck on, on android. The normal client just connects normally.
Now my question is, is there something wrong with my android code, or is it just the device, or wifi connection?
If it helps, I tried testing it on my samsung galaxy nexus, which is rooted.
Thanks in advance.
I have an web server which is getting a lot of messages to the same topic and is returning response messages to another topic.
I am currently re-using the same MQTT client instance both for the callback and for sending the response messages by keeping the MQTT client connected all the time.
However, after one cycle of receiving a message and sending a response, I am able to receive another message but cannot send the response - I have to restart the application server.
Is it a good approach to have a single MQTTclient instance? Is it OK to keep it connected all the time? What's the best approach for this kind of requirement?
Here is my code:
public static void registerCallBack(String topicName, String userName,
String password, String clientId, MqttCallback callback,
MqttClient client) {
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
options.setKeepAliveInterval(30);
options.setUserName(userName);
options.setPassword(password.toCharArray());
// Connect to Broker
try {
options.setSocketFactory(SslUtil.getSocketFactory(
ManagerProps.MQTT_BROKER_CA_FILE.getValue(), ""));
client.setCallback(callback);
client.connect(options);
client.subscribe(topicName, 0);
log.info("successfuly registered callback to topic " + topicName);
} catch (MqttException me) {
log.error("MqttException, " + me);
} catch (Exception e) {
log.error("Exception, " + e);
}
}
public static String publishMessage(MqttClient client, String message,
String topic, String userName, String password) {
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
options.setKeepAliveInterval(30);
options.setUserName(userName);
options.setPassword(password.toCharArray());
try {
MqttMessage msg = new MqttMessage();
msg.setPayload(message.getBytes());
client.publish(topic, msg);
} catch (MqttException e) {
log.error("MqttException, " + e);
} catch (Exception e) {
log.error("Exception, " + e);
}
return message;
}
I was seeing something similar, and got this to work:
final CallbackConnection connection = mqtt.callbackConnection();
connection.listener(new org.fusesource.mqtt.client.Listener() {
public void onConnected() {
}
public void onDisconnected() {
}
public void onFailure(Throwable value) {
value.printStackTrace();
System.exit(-2);
}
public void onPublish(UTF8Buffer topic, Buffer msg, Runnable ack) {
String body = msg.utf8().toString();
if( body.startsWith("REPLY: ")) {
// Don't reply to your own reply
System.out.println("Replied");
System.out.println("");
} else {
try{
byte[] reply = "REPLY: Hello Back".getBytes();
connection.publish(destination, reply, QoS.AT_MOST_ONCE, true, null) ;
msg.clear();
}catch (Exception e){
e.printStackTrace();
}
}
}
});
I have used javapns for pushing notifications to ios and android.gcm.server to push notification for android devices. But when I sent one notifications to many devices each device get multiple number of copies of the notification sent. Sometimes this number is 2 and sometimes 3. Hardly it delivers only one which I expect always. Any Ideas ?
My code is as below
public void pushNotificationsToAndroid(String pushMessage,
String contentType, String content, String notification_id,
List<String> devices) {
try {
Sender sender = new Sender(
properties
.getProperty("notification.android.senderIdDemo"));
com.google.android.gcm.server.Message message = new com.google.android.gcm.server.Message.Builder()
.collapseKey("1").timeToLive(3).delayWhileIdle(true)
.addData("message", pushMessage)
.addData("content_type", contentType)
.addData("content", content)
.addData("notification_id", notification_id).build();
MulticastResult result = sender.send(message, devices, 1);
if (result.getResults() == null) {
System.out.println(result.getFailure());
logger.debug("getFailure() of sender.send() method :",
result.getFailure());
}
} catch (Exception exception) {
logger.error("erorr push notification ");
}
System.out.println("sent not at " + new Date());
logger.debug(
"exit pushNotificationsToAndroid() method : current time is ",
new Date());
}
public void pushNotificationsToIOS(String pushMessage, String contentType,
String content, String notification_id, List<String> devices)
{
boolean production = true;
String password = properties
.getProperty("notification.ios.password");
String keyStroke = properties
.getProperty("notification.ios.certFileName");
AppleNotificationServer jksServer = null;
try {
jksServer = new AppleNotificationServerBasicImpl(keyStroke,
password, ConnectionToAppleServer.KEYSTORE_TYPE_JKS,
production);
} catch (KeystoreException keystoreException) {
logger.error("erorr creating jksServer");
}
PushNotificationPayload payload = PushNotificationPayload.complex();
try {
payload.addAlert(pushMessage);
} catch (JSONException e2) {
logger.error("erorr creating payload alert");
}
try {
payload.addCustomDictionary("content_type", contentType);
} catch (JSONException e1) {
logger.error("erorr creating payload content_type");
}
try {
payload.addCustomDictionary("content", content);
} catch (JSONException e1) {
logger.error("erorr creating payload content");
}
try {
payload.addCustomDictionary("notification_id", notification_id);
} catch (JSONException e1) {
logger.error("erorr creating payload notification_id");
}
PushNotificationManager pushManager = new PushNotificationManager();
try {
pushManager.initializeConnection(jksServer);
} catch (CommunicationException | KeystoreException e) {
logger.error("erorr connecting Server");
}
try {
List<PushedNotification> notifications = pushManager
.sendNotifications(payload, Devices.asDevices(devices));
} catch (CommunicationException | KeystoreException e) {
logger.error("erorr push notifications");
}
}
In android official site says about some reasons for duplicate message conditions .
I'm doing an app which needs to communicate with TCP sockets. I set up a Service which is my TCP Server and an activity which is my TCP Client.
I have a big delay from sending a message and receiving an answer from the server, like 10 or more seconds. After some days of researches, I found how to set timeout on the client request and all start to work fine.
So my question is, is it mandatory to set up timeout for a TCP connection, otherwise it doesn't work or something else is wrong with my implementation?
Here's my Client code:
public static void sendTCP(final InetAddress senderAddr, final String Msg, final int serverPort) {
Thread tclient = new Thread(){
public void run() {
boolean connected;
Socket socket = new Socket();
try {
Log.d("TCP", "Client: Connecting...");
socket.bind(null);
socket.connect((new InetSocketAddress(senderAddr, serverPort)), 1000);
connected = true;
try {
Log.d("TCP", "Client: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(Msg);
out.close();
}
catch (Exception e) {
Log.e("TCP", "Client: Error sending.", e);
}
} catch (Exception e) {
Log.e("TCP", "Client: Error connecting.", e);
connected = false;
}
finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
Log.d("TCP", "Client: Connection Closed.");
} catch (IOException e) {
Log.e("TCP", "Client: Error closing connection.", e);
}
}
}
}
}
};
tclient.start();
}
And Server's:
public void onStart(Intent intent, int startid) {
t = new Thread(){
public void run() {
try {
Boolean end = false;
Log.d("TCP", "Server: Creating server.");
ServerSocket ss = new ServerSocket(TCPPORT);
while(!end) {
//Server is waiting for client here, if needed
Log.d("TCP", "Server: Waiting on packet!");
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = input.readLine();
Log.d("TCP", "Server: Message received from client: "+st);
InetAddress senderAddr = s.getInetAddress();
senderAddrString= senderAddr.getHostAddress();
myAddrString = GetLocalIpAddress();
myAddr = InetAddress.getByName(myAddrString);
if (senderAddr.equals(myAddr)) {
}
else {
//Estraggo dal pacchetto ricevuto
try {
StringTokenizer tokens = new StringTokenizer(st, "|");
flag = tokens.nextToken();
userid = tokens.nextToken();
payload = tokens.nextToken();
}
catch (Exception e) {
Log.e("TCP", "Server: Errore estrazione dati.");
}
if (flag.equals(Constants.flag_scan_answer)) {
Log.d("TCP", "Server: Flag answer");
//devo passare i dati ad un database ScanActivity
//database(senderAddrString,userid);
System.out.println("RISPOSTA RICEVUTA DAL SERVICE TCP");
System.out.println("FLAG " + flag);
System.out.println("USERID " + userid);
System.out.println("PAYLOAD " + payload);
announceReceivingPacket();
}
else {
Log.d("TCP", "Server: CASO NON PREVISTO");
}
}
s.close();
}
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
t.start();
}
it's mandatory to set up timeout for a TCP connection
It isn't mandatory but it's a very good idea. Start by setting it to double or triple the expected service time and adjust so you don't get false positives. The default read timeout is infinity, and I have seen entire platforms fail in a way that wasn't detectable by the reader in any other way than a read timeout.
See here for relevant quotations.
The connect call
socket.connect((new InetSocketAddress(senderAddr, serverPort)), 1000);
can be BeginConnect with a callback that automatically reports failures and timeouts as well as successful connections. At this point you can use BeginSend and BeginReceive on the socket.