jquery stomp websockets server reconnection reinitialization - java

I have a websocket app that connects to my Java backend via stomp.js file.
function connect() {
var socket = new SockJS('<?php echo $rootbasename;?>wsconnect');
stompClient = Stomp.over(socket);
stompClient.debug = null;
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
console.log('/queue/messages/' + widgetId + "/" + $.cookie(cookiename));
stompClient.subscribe('/queue/messages/' + widgetId + "/" + $.cookie(cookiename), function (result) {
//code here
}, {userToken: $.cookie(cookiename), widgetId: widgetId});
stompClient.subscribe('/queue/makereadresult/' + widgetId + '/' + $.cookie(cookiename), function (result) {
});
But, what if my java backend server will reboot? I want customers not to notice any change. Is there a way to auto-reconnect on connection lost? Or any way to make it smooth for clients?

When you are connecting you can pass in error callback. In there you could have reconnect logic.
For example stomp has this method
client.connect(login, passcode, connectCallback, errorCallback);
and in errorCallback just call connectCallback.

Related

Java client cant connect with NodeJS server on heroku

So I have this Javascript server:
const net = require('net');
var port = process.env.PORT || 3001;
net.createServer(function (sock){
console.log('CONNECTED: ' + sock.remoteAddress + ":" + sock.remotePort);
sock.on('data', function(data){
console.log(data.toString());
});
sock.on('close', function(data){
console.log('DISCONNECTED: ' + sock.remoteAddress + ":" + sock.remotePort);
});
sock.on('error', function(error){
console.log(error);
});
}).listen(port, '0.0.0.0');
console.log('Listening on: ' + port);
And I use this to connect my Java client:
public void connect () {
System.out.println("Connecting with: " + host + ":" + port);
try {
this.socket = new Socket(this.host, this.port);
System.out.println("Connected!");
} catch (IOException e) {
e.printStackTrace();
}
}
And it works when I try it local but whenever I upload it to heroku it never logs a CONNECTED message or any received data so I don't think it connects.
I'm using this as ip/port to connect my client: .herokuapp.com:heroku.env.PORT not literally ofcourse, I use the port heroku gives to my application on launch since I do see the Listening on: message.
Am I doing something wrong? Or does heroku not support sockets?
Your client should connect to <appname>.herokuapp.com on port 80 or 443. The PORT var is for internal binding only.

iOS Push Notifications to a topic

I have an Ionic app (client), with a Java 8 backend (server), and I have set up push notifications.
client
let topics: string[] = [this.personModelLoggedIn.uid];
const options: PushOptions = {
android: {
senderID: "XXXXXXXXXXXX",
sound: "true",
vibrate: "true",
topics: topics
},
ios: {
senderID: "XXXXXXXXXXXX",
alert: "true",
badge: true,
sound: "true",
topics: topics
},
windows: {}
};
For Android, I can receive notifications, send from the following:
server
private String sendAndroidPushNotification(String device_token, String topics, String title, String message)
throws Exception {
String pushMessage = null;
if (device_token != null && !device_token.equals("null")) {
pushMessage = "{\"data\":{\"title\":\"" + title + "\",\"message\":\"" + message + "\"},\"to\":\""
+ device_token + "\"}";
} else {
pushMessage = "{\"data\":{\"title\":\"" + title + "\",\"message\":\"" + message + "\"},\"to\": \"/topics/"
+ topics + "\"}";
}
// Create connection to send FCM Message request.
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send FCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(pushMessage.getBytes());
return "Android Push Notification: " + conn.getResponseCode() + " " + conn.getResponseMessage() + " - " + pushMessage;
}
Problem
I have the following code for iOS, but the client does not receive the push notifications.
/**
* import com.notnoop.apns.APNS; import com.notnoop.apns.ApnsService;
* https://github.com/notnoop/java-apns.
*/
private String sendIOSPushNotification(String device_token, String topics, String title, String message)
throws Exception {
ApnsService service = APNS.newService().withCert(PATH_TO_P12_CERT, CERT_PASSWORD).withSandboxDestination()
.build();
String payload = APNS.newPayload()
// .customFields(map)
.alertBody(title + " " + message).sound("default").build();
service.push(Utilities.encodeHex(topics.getBytes()), payload);
return "iOS Push Notification: " + title + " " + message;
}
If you look at the com.notnoop.apns api, it is supposed to push to a device token, however, I need it to rather push to a uid. I have implemented the above code to push to a uid, but it doesn't work.
Question
Id it possible for the com.notnoop.apns api to push notifications to a topic? Otherwise, is there another api that will be able to do this?
If neither is possible, should the client rather listen on the device token? But the problem here is, that the sender of the push notification does not know the receivers device token. The sender does know the receivers uid though.
Thanks

Jetty: Client closes TCP connection before receiving a response from a request

I am trying to make a POST request to a Microsoft IIS Webserver (5.1) using the Jetty Client (v9). However this will result in an EOFException on the client-side. After some investigation with wireshark I found that the TCP connection is closed by the client immediately after the request is sent and before a response is arrived.
If I am making the same request to a Tomcat-Server, it works perfectly.
Does someone know this issue or what could lead to it? Bug in Jetty?
Client:
if (jettyClient != null) {
if (jettyClient.isStarted()) {
remoteHostname = httpAddress.getRemoteUrl().substring(7);
serviceURI = httpAddress.getRemoteService();
logger.debug("post an: " + httpAddress.getRemoteUrlPortService());
Request request = jettyClient.POST(httpAddress.getRemoteUrlPortService());
request.version(httpVersion);
request.header(HttpHeader.CONTENT_TYPE, httpContentType);
request.header(HttpHeader.CONTENT_LENGTH, Integer.toString(msg.length()));
request.header(HttpHeader.HOST, remoteHostname + ":" + httpAddress.getRemotePort());
request.timeout(httpTimeout, TimeUnit.MILLISECONDS); // 20000
request.agent(ApplicationMeta.name + " " + ApplicationMeta.version);
request.method(HttpMethod.POST);
request.header("SOAPAction", soapAction);
request.content(new StringContentProvider(msg));
HTTPIncomingResponseSet set = null;
try {
ContentResponse response = request.send();
} catch (ExecutionException e) {
// ....
}
}

Server does not respond to concurrent requests in HTTP/1.1 Client using Java

I'am trying to implement a simple HTTP/1.1 client application against a remote HTTP server. If I have a 301 Moved Permanently response from server, I will try to download the file from it's new location given in server's response. I am able to send first GET message to server and retrieve the new URL where the file I asked was moved.
The problem is that when I send second GET request from my client with new location of the file, server returns null. Not sure if anything goes wrong with writing the client message or reading the server response. Here is my code, any help is appreciated.
else if(serverMessage.equals("HTTP/1.1 301 Moved Permanently"))
{
System.out.println(" A new permanent URL is assigned to the file " + fileName);
serverMessage="";
lineCount=0;
while((serverMessage = reader.readLine()) != null)
{
lineCount++;
System.out.println("reply: " + serverMessage);
if(serverMessage.indexOf("Location") >= 0 )
{
for(int x=serverMessage.indexOf("Location")+10; x<serverMessage.length(); x++)
{
newURL= newURL + serverMessage.charAt(x);
}
}
}
System.out.println("newURL : " + newURL);
host = findHost(newURL);
path = findPath(newURL);
fileName=findFileName(newURL);
clientMessage = "GET ";
clientMessage = clientMessage + path;
clientMessage = clientMessage + " HTTP/1.1\r\nHost: ";
clientMessage = clientMessage + host;
clientMessage = clientMessage + "\r\n\r\n";
System.out.println("client message: \"" + clientMessage +"\"");
writer.newLine();
writer.write(clientMessage);
writer.flush();
serverMessage = reader.readLine();
System.out.println("reply2: " + serverMessage); //returns null!!!
while((serverMessage=reader.readLine())!=null)
{
System.out.println("reply2: " + serverMessage);
}
}
EDIT: Variables of client message are the followings (they all work correctly, tested for existing file - successfully downloaded!)
newURL : http://wlab.cs.bilkent.edu.tr/~cs421/pa1/302-redirect-success.txt
host2: wlab.cs.bilkent.edu.tr
path2: /~cs421/pa1/302-redirect-success.txt
fileName2: 302-redirect-success.txt
Are you using a persistent URLConnection / HttpURLConnection?
You may be receiving null if the connection has been closed by the server.
If you are using persistent connections, the server might have not had the time to respond.
This might describe the problem a little better. Check out the timeout given in doHttpUrlConnectionAction(String desiredUrl). You might find the answer there.
If this is your problem, you can try to do multiple reads at 0.1 second intervals for say ... 1-5 seconds. This is to make sure you get the response fast and don't have to wait the full timeout to make sure that the server has responded.

J2ME SIP connection VIA header

I send INVITE to a sip server in a J2ME app and use rtp for data transmision.There is a conflict in VIA header which is that,implecite via header contain UDP instead of rtp. But I haven't use 'upd' any where in my code.If we consider the JAINSIP we can modify the VIA header header.But j2m2 api doesn't allow to modify the VIA header(here).
How can I solve this?how to avoid implicitly adding udp to VIA header in my request.Where I should see again??
Here is my sending INVITE Code
try { final String ip = scn.getLocalAddress();
contact = "sip:user#" + scn.getLocalAddress() + ":" + scn.getLocalPort();
scc = (SipClientConnection) Connector.open("sip:user#xxx.xxx.xxx.x:5060;transport=tcp");
scc.setListener(this);
scc.initRequest("INVITE", scn);
scc.setRequestURI("sip:user#xxx.xxx.xxx.x:5060;transport=tcp");
scc.setHeader("From", "sip:user#" + scn.getLocalAddress() + ":" + scn.getLocalPort() + ";transport=tcp");
scc.setHeader("To", "sip:user#xxx.xxx.xxx.x:5060;transport=tcp");
scc.setHeader("Contact", contact);
System.out.println("Session id is :" + sId);
scc.setHeader("Session-Id", sId);
scc.setHeader("Content-Type", "application/sdp");
String sdp = "....";
OutputStream os = scc.openContentOutputStream();
os.write(sdp.getBytes());
os.close();

Categories

Resources