I am trying to connect websocket server from Android. It is working successfully when doing request to localhost server via HTTP call with port. However for hosted server with HTTPS it is not working and getting below error.
06-08 12:42:44.055 19985-20130/com.package
E/WebSocketsConnectionProvider: onError
java.lang.RuntimeException: unkonow schemehttps
This code I am using for :
mStompClient = Stomp.over(WebSocket.class, "https://api.testapp.com/sc/websocket/?access_token=" + sessionManager.getAccessToken());
mStompClient.topic("/topic/test/" + patientAppointmentItem.getAppointmentId())
.subscribe(topicMessage -> {
toast(""+ topicMessage.getPayload());
});
mStompClient.send("/app/test/" + patientAppointmentItem.getAppointmentId() + "/chat.addUser", obj.toString()).subscribe();
List<StompHeader> headers = new ArrayList<>();
headers.add(new StompHeader(StompHeader.id, id));
headers.add(newStompHeader(StompHeader.USERROLE,sessionManager.getRole()));
mStompClient.lifecycle().subscribe(lifecycleEvent -> {
switch (lifecycleEvent.getType()) {
case OPENED:
Log.i(TAG, "Stomp connection opened");
break;
case ERROR:
Log.i(TAG, "Stomp connection error");
break;
case CLOSED:
Log.i(TAG, "Stomp connection closed");
break;
}
});
mStompClient.connect(headers);
NOTE : We have Node js application already using this https websocket
service in web application and it is working well. So I believe it's
not any proxy issue or other issue with server.
Working Link on localhost server : http://localhost:8080/sc/websocket
Live server link : https://api.testapp.com/sc/websocket
Please guide if I am doing any mistake.
Thanks in advance.
Related
This is based on this post answered by Xlythe. I am also using P2P_STAR strategy and trying to transfer the file (1GB) asUri to other 2 devices but when it received in other device it is showing some KB(1.98 kb) as file size and receiving below logs in PayloadTransferUpdate.Status.IN_PROGRESS continuously.
2022-05-23 04:27:29.233 32032-32032/com.google.location.nearby.apps.rockpaperscissors I/TAG: IN_PROGRESS:
2022-05-23 04:27:30.375 32032-32032/com.google.location.nearby.apps.rockpaperscissors I/TAG: IN_PROGRESS:
2022-05-23 04:27:31.215 32032-32032/com.google.location.nearby.apps.rockpaperscissors I/Service: onEndpointFound: endpoint lostEAP0
2022-05-23 04:27:31.728 32032-32032/com.google.location.nearby.apps.rockpaperscissors I/TAG: IN_PROGRESS:
2022-05-23 04:27:32.582 32032-32032/com.google.location.nearby.apps.rockpaperscissors I/Service: onEndpointFound: endpoint found, connectingEAP0
2022-05-23 04:27:33.151 32032-32032/com.google.location.nearby.apps.rockpaperscissors I/TAG: IN_PROGRESS:
2022-05-23 04:27:33.997 32032-32032/com.google.location.nearby.apps.rockpaperscissors I/TAG: IN_PROGRESS:
Any idea why this is happening or is there any other way to send such a large file ?
I have few more doubts in that.
Why always that discovery device lost the connection and again its founding the endpoint (you can check in the above log)?
If we connected with internet or Wi-Fi and once file has been received by all other devices, I wanted to stopAdvertiser but its not happening as I am connected with internet or Wi-Fi, which means Bluetooth is always enabled. So my doubt is if device is connected with local Wi-Fi or internet, nearby connection api will never call stopAdvertiser/stoDiscovery ?
Note - I have tried to send some KB file which works perfectly.
Below is my code:
public static final PayloadCallback payloadCallback = new PayloadCallback() {
#Override
public void onPayloadReceived(String endpointId, Payload payload) {
Log.i(TAG,"onPayloadReceived");
if (payload.getType() == Payload.Type.FILE){
Uri uri = payload.asFile().asUri();
Log.d(TAG,"received uri: " + uri);
try {
// Copy the file to a new location.
InputStream in = mContext.getContentResolver().openInputStream(uri);
copyStream(in, new FileOutputStream(new File(Environment.getExternalStorageDirectory().toString()+"/Download/",fileName)));
Toast.makeText(mContext,"File has been received successfully", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onPayloadTransferUpdate(String endpointId, PayloadTransferUpdate update) {
switch(update.getStatus()){
case PayloadTransferUpdate.Status.SUCCESS:
Log.i(TAG,"Successfully send the file: " + update.getStatus());
break;
case PayloadTransferUpdate.Status.FAILURE:
Log.i(TAG,"Failed:");
break;
case PayloadTransferUpdate.Status.CANCELED:
Log.i(TAG,"CANCELED:");
break;
case PayloadTransferUpdate.Status.IN_PROGRESS:
Log.i(TAG,"IN_PROGRESS:");
break;
}
}
};
I am trying to connect signalR from the android client. I have already setup signalR hub and its working properly with javascript client on the browser. javascript client able to sent bearer-token and on the server side, I am able to get user identity.
But android java client is not able to send bearer token on. I am using https://github.com/SignalR/java-client library (As I am not using SIgnalR-core so not using latest SIgnalR core library)
connection = new HubConnection(serverUrl);
connection.getHeaders().put("Authorization","Bearer XYZ");
proxy = connection.createHubProxy(hubName);
When I run this code, I got an error
java.lang.InterruptedException: Operation was canceled
But when I don't send AUthorization header with the request then on server-side SIgnalR OnConnected() method called successfully.
The issue seems to be with sending Authorization header with the request.
For reference, the following is code to show how token authentication is implemented on the server-side
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
Provider = new QueryStringOAuthBearerProvider()
});
var hubConfiguration = new HubConfiguration
{
Resolver = GlobalHost.DependencyResolver,
};
map.RunSignalR(hubConfiguration);
});
ConfigureAuth(app);
I have tried calling it by removing authorization from the server. Then it called successfully. But not works when called with Authorization header.
When I tried connection without Authorization then on server-side OnCOnnected method called but Context. Identity is null.
android Java code for connecting to SignalR client
Platform.loadPlatformComponent(new AndroidPlatformComponent());
// Create Connection
connection = new HubConnection(serverUrl);
connection.getHeaders().put("Authorization","Bearer XYZ");
// Create Proxy
proxy = connection.createHubProxy(hubName);
// Establish Connection
ClientTransport clientTransport = new
ServerSentEventsTransport(connection.getLogger());
SignalRFuture<Void> signalRFuture = connection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException e) {
return false;
} catch (ExecutionException e) {
return false;
}
return true;
If you are using Websocket, try this
https://github.com/doctorcareanywhere/java-client
build signalr-client-sdk and import the jar to your project
eg.
implementation files('libs/signalr-client-sdk.jar')
I am facing the issue to retrieve offline message in android apps using smack api from XMPP Mongoose server. As per the code flow Try to retrive offline message when user become login in xmpp mongoose server before sending available presence to mongoose server.
Tried with two different way to retrieve offline message still not able to find working solution for the same. Both method which i tried those all things are explain below with detail.
Below Api we are using for the xmpp connection and all other extension :
// Smack (XMPP Client Library)
compile 'org.igniterealtime.smack:smack-android:4.1.6'
compile 'org.igniterealtime.smack:smack-tcp:4.1.6'
compile 'org.igniterealtime.smack:smack-im:4.1.6'
compile 'org.igniterealtime.smack:smack-android-extensions:4.1.6'
Tried retrive offline message Using offlineMessageManager
Below is code which I tried to retrieve offline message after login and before send available presence to server
try {
Boolean isFelxibleRetrievalSupport = offlineMessageManager.supportsFlexibleRetrieval();
Iterator i = (Iterator) offlineMessageManager.getMessages();
while (i.hasNext())
{
Message msg = i.next();
System.out.println("Got text [" + msg.getBody() + "] from [" + msg.getFrom() + "]");
} catch (XMPPException e)
{
System.out.println("Error Offline Message.");
e.printStackTrace();
}
catch (SmackException.NotConnectedException e)
{
System.out.println("Error Offline Message. No connection");
e.printStackTrace();
}
catch (SmackException.NoResponseException e)
{
System.out.println("Error Offline Message. No Reponse");
e.printStackTrace();
}
Issue case 1:
Below is exception detail which generate when above code execute
I got Exception when execute below line of code.
Iterator i = (Iterator) offlineMessageManager.getMessages();
Below is exception description which Generate when above line execute
org.jivesoftware.smack.XMPPException$XMPPErrorException: XMPPError: service-unavailable - cancel
Issue Case 2:
If checking is Flexible offline message supported from android code using smack from xmmp mongoose server so i got false value. Below is code which i used for testing.
Boolean isFelxibleRetrievalSupport = offlineMessageManager.supportsFlexibleRetrieval();
Issue Case 3:
When I try to retrieve supported features using below method using smack code like below.
ServiceDiscoveryManager manager = ServiceDiscoveryManager
.getInstanceFor(connection);
List AllFetures = manager.getFeatures();
Below is features list which i retrived:
http://jabber.org/protocol/bytestreams,
jabber:iq:privacy, urn:xmpp:ping,
http://jabber.org/protocol/commands,
jabber:iq:version,
jabber:iq:last,
http://jabber.org/protocol/xdata-validate,
http://jabber.org/protocol/xhtml-im,
vcard-temp,
http://jabber.org/protocol/chatstates,
urn:xmpp:receipts, urn:xmpp:time,
http://jabber.org/protocol/xdata-layout,
http://jabber.org/protocol/muc,
http://jabber.org/protocol/disco#items,
http://jabber.org/protocol/disco#info,
http://jabber.org/protocol/caps,
jabber:x:data
Tried to retreive offline message Using package listener from XMPP MongooseIM
below is code which i tried using package listener from smack api 4.1.6.
private static final StanzaFilter MESSAGE_PACKET_FILTER= new OrFilter(StanzaTypeFilter.MESSAGE);
configuration = XMPPTCPConnectionConfiguration.builder()
.setServiceName(SERVICE_NAME)
.setHost(KDevelopmentXMPPServer)
.setPort(PORT)
.setSendPresence(false)
.build();
// Create Connection object of xmpp connection with configured detail
connection = new XMPPTCPConnection(configuration);
connection.addAsyncStanzaListener(new StanzaListener() {
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
Log.d("CheckPacket", "OfflineMEssage");
Message message = (Message) packet;
if (message != null) {
if (message.getBody() != null) {
Log.i("XMPPClient", "Got text [" + message.getBody()
+ "] from [" + message.getFrom() + "]");
}
}
}
}, MESSAGE_PACKET_FILTER);
connection.login(user, password);
Thanks In Advance, Please anybody help me for best working solution for my critical issue.
The issue is in trying to fetch offline messages before
sending the initial presence. XEP-0160 states:
When the recipient next sends non-negative available presence to the server, the server delivers the message to the resource that has sent that presence. [...]
MongooseIM works with accordance to this recommendation.
You already pointed out what is signaled by isFlexibleRetrievalSupport - the server does not support flexible offline message retrieval.
I know I am writing this too late, but if someone like me who is hunting for same query as in "how to save and get archive messages in android app" can refer this answer :
Note :
this is implemented in the lastest version
Requrirements :
lastest openfire as of now 4.1.4
install Archives plugin in openfire
MamManager mamManager = MamManager.getInstanceFor(connection);
boolean isSupported = mamManager.isSupportedByServer();
if (isSupported) {
MamManager.MamQueryResult mamQueryResult = mamManager.queryArchive(500);
List<Forwarded> forwardedMessages = mamQueryResult.forwardedMessages;
Forwarded d = forwardedMessages.get(0);
}
Please Refer : Documention for MamManager Class
I am working on WebSocket server implementation on Xamarin for an Android project, here I have Monoframework MDK 3.10.0.23 and Xamarin.android 4.18 which are latest ones.
For server implementation I'm using HttpListener and HttpListenerContext and evaluating the context.Request.IsWebSocketrequest, which is always getting false, when I run it on a Google Nexus 10.
{
Console.WriteLine("WS Server Started Waiting for connection");
HttpListenerContext httpListenerContext = await httpListener.GetContextAsync();
if (!httpListenerContext.Request.IsWebSocketRequest)
{
WebSocketContext webSocketContext;
Console.WriteLine("Got a Valid WebSocket connection request");
try
{
webSocketContext = await httpListenerContext.AcceptWebSocketAsync(subProtocol:null);
}
catch (Exception e)
{
httpListenerContext.Response.StatusCode = 500;
httpListenerContext.Response.Close();
Console.WriteLine("Exception: {0}", e);
return;
}
WebSocket webSocket = webSocketContext.WebSocket;
if (webSocket == null)
Console.WriteLine ("WebSocket obj is null");
//ProcessRequest(httpListenerContext);
}
else
{
Console.WriteLine("Got a Bad WebSocket connection request");
httpListenerContext.Response.StatusCode = 400;
httpListenerContext.Response.Close();
}
}
Please help and suggest the problem here creating the HttpListener object for http:// local host at 9090
websockets initiates connection via http with the request to upgrade. if the server do not reply with the 101 response code, it is a sign that there is a problem in connection. the request to connect via websockets uses ws://yourdomain.com/nameOfApplicationEndPoint or wss in cases of ssl connection. i used this for my android project org.java-websocket:Java-WebSocket:1.3.0 and you can get a simple example here http://www.elabs.se/blog/66-using-websockets-in-native-ios-and-android-apps
I am currently developing android XMPP client to communicate with the Tigase server setup locally.Before starting development on Android I am writing a simple java code on PC to test connectivity with XMPP server.My XMPP domain is my pc name "mwbn43-1" and administrator username and passwords are admin and tigase respectively.
Following is the snippet of the code I am using
class Test {
public static void main(String args[])throws Exception
{
System.setProperty("smack.debugEnabled", "true");
XMPPConnection.DEBUG_ENABLED = true;
ConnectionConfiguration config = new ConnectionConfiguration("mwbn43-1", 5222);
config.setCompressionEnabled(true);
config.setSASLAuthenticationEnabled(true);
XMPPConnection con = new XMPPConnection(config);
// Connect to the server
con.connect();
con.login("admin", "tigase");
Chat chat = con.getChatManager().createChat("aaphadke#mwbn43-1",
new MessageListener() {
public void processMessage(Chat chat, Message message) {
// Print out any messages we get back to standard out.
System.out.println("Received message: " + message);
}
});
try {
chat.sendMessage("Hi!");
}
catch (XMPPException e) {
System.out.println("Error Delivering block");
}
String host = con.getHost();
String user = con.getUser();
String id = con.getConnectionID();
int port = con.getPort();
boolean i = false;
i = con.isConnected();
if (i)
System.out.println("Connected to host " + host + " via port " + port + " connection id is " + id);
System.out.println("User is " + user);
con.disconnect();
}
}
When I run this code I get following error
Exception in thread "main" Resource binding not offered by server:
at org.jivesoftware.smack.SASLAuthentication.bindResourceAndEstablishSession(SASLAuthenticatio n.java:416) at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:331)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:395)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:349)
at Test.main(Test.java:26)
I found this articles on the same problem but no concrete solution
here
Could anyone please tell me the solution for this problem.I checked the XMPPConnection.java file in the Smack API and it looks the same as given in the link solution.
Thanks,
Ameya
I found the solution to the problem as given in here
These are the lines I should add before I connect to the server
ConnectionConfiguration config = new ConnectionConfiguration("mwbn43-1", 5222);
config.setSASLAuthenticationEnabled(false);
XMPPConnection xmpp = new XMPPConnection(config);
Thanks for all your help
I think this is a problem with library, a bug. It does not handle protocol correctly. Before the user is authenticated there is no point of sending resource bind, hence it is not advertised by the server. The client should not complain about it.