Setting up Signal R in Android: Crash/Hung Issue - android

I followed THIS tutorial to set up a .NET Backend for my Android app to implement Signal R. I set up a SignalR Self-Hosted backend.
Here's my Backend Code in a Console Project:
namespace SignalRSelfHost
{
class Program
{
static void Main(string[] args)
{
// This will *ONLY* bind to localhost, if you want to bind to all addresses
// use http://*:8080 to bind to all addresses.
// See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
// for more information.
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class MessageHub : Hub
{
public static event Action<string, string> MessageReceived = delegate { };
public void SendMessage(string name, string message)
{
MessageReceived(name, message);
}
}
public class CustomType
{
public string Name;
public int Id;
}
}
My Android Code:
Handler handler;
TextView statusField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
handler = new Handler();
statusField = (TextView) findViewById(R.id.statusField);
Platform.loadPlatformComponent(new AndroidPlatformComponent());
// Change to the IP address and matching port of your SignalR server.
String host = "http://192.168.1.5:8080/";
HubConnection connection = new HubConnection( host );
HubProxy hub = connection.createHubProxy( "MessageHub" );
ClientTransport transport = new ServerSentEventsTransport(connection.getLogger());
SignalRFuture<Void> awaitConnection = connection.start(transport);
try {
awaitConnection.get();
}
catch (InterruptedException e) {
Log.d("CHECK", e.toString());
e.printStackTrace();
} catch (ExecutionException e) {
Log.d("CHECK", e.toString());
e.printStackTrace();
}
hub.subscribe(this);
try {
hub.invoke( "SendMessage", "Client", "Hello world!" ).get();
hub.invoke( "SendCustomType",
new CustomType() {{ Name = "Universe"; Id = 42; }} ).get();
} catch (InterruptedException e) {
// Handle ...
} catch (ExecutionException e) {
// Handle ...
}
}
public void UpdateStatus(String status) {
final String fStatus = status;
handler.post(new Runnable() {
#Override
public void run() {
statusField.setText(fStatus);
}
});
}
public class CustomType
{
public String Name;
public int Id;
}
However, I end up with a screen that hangs and it displays nothing and the app stops responding. The android logger displays the following error:
java.util.concurrent.ExecutionException: java.net.ConnectException:
failed to connect to localhost/127.0.0.1 (port 80) after 15000ms:
isConnected failed: ECONNREFUSED (Connection refused)
Is my code correct and have I followed the guide properly? It's a very straight forward guide but this issue comes up. Can someone help out?
EDIT:
This is a very similar Question, in fact it describes the same issue. However it didn't do me any good. If you notice my android code, I've already made those changes proposed in that question. Still didn't rectify the issue.
Stacktrace
java.util.concurrent.ExecutionException: java.net.SocketTimeoutException: failed to connect to / 192.168.1.5(port 8080) after 15000ms
at microsoft.aspnet.signalr.client.SignalRFuture.get(SignalRFuture.java: 112)
at microsoft.aspnet.signalr.client.SignalRFuture.get(SignalRFuture.java: 102)
at com.example.dinuka.signalrtest.Main2Activity.onCreate(Main2Activity.java: 40)
at android.app.Activity.performCreate(Activity.java: 6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java: 1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2655)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2767)
at android.app.ActivityThread.access$900(ActivityThread.java: 177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1449)
at android.os.Handler.dispatchMessage(Handler.java: 102)
at android.os.Looper.loop(Looper.java: 145)
at android.app.ActivityThread.main(ActivityThread.java: 5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java: 372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 1195)
Caused by: java.net.SocketTimeoutException: failed to connect to / 192.168.1.5(port 8080) after 15000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java: 169)
at libcore.io.IoBridge.connect(IoBridge.java: 122)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java: 183)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java: 456)
at java.net.Socket.connect(Socket.java: 882)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java: 139)
at com.android.okhttp.Connection.connect(Connection.java: 1194)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java: 392)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java: 295)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java: 373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java: 323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java: 491)
at microsoft.aspnet.signalr.client.http.java.NetworkRunnable.run(NetworkRunnable.java: 72)
at java.lang.Thread.run(Thread.java: 818)

I had similar issue a few days ago and this Github issue helped:
https://github.com/SignalR/java-client/issues/63
Basically what I did was modify the WebsocketTransport.java in the signalr-client-sdk project. Replace:
uri = new URI(url);
with
uri = new URI(url.replace("http://", "ws://"));
around line 86 in the source code.
I can now connect and send message and recieve raw data but cannot subscribe to events...
Hope this helps you get passed your problem.

Related

AWS IoT Android application over MQTT throws MqttException (0) - java.io.IOException: Already connected

I am trying to use 'Authenticate using Cognito-Identity with Cognito user pool' in my Android application. My Cognito user pool authentication works well, when I run that separately and I had seen a JWTToken as well. When I run the the 'PubSub' sample application with Unauthenticated role, it worked as expected. When I integrate these two features in one application, the application threw following error.
W/System.err: MqttException (0) - java.io.IOException: Already connected
W/System.err: at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
W/System.err: at java.lang.Thread.run(Thread.java:761)
W/System.err: Caused by: java.io.IOException: Already connected
W/System.err: at java.io.PipedOutputStream.connect(PipedOutputStream.java:100)
W/System.err: at java.io.PipedInputStream.connect(PipedInputStream.java:195)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketReceiver.<init>(WebSocketReceiver.java:42)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule.start(WebSocketSecureNetworkModule.java:78)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
W/System.err: ... 1 more
I have been trying to resolve this issue since last Thursday and still stuck at the same place. Really No idea where should i check.!
I am adding my Authentication(Cognito user pool authentication) activity and Connect activity.
AmazonCognitoIdentityProviderClient identityProviderClient = new
AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), new ClientConfiguration());
identityProviderClient.setRegion(Region.getRegion(Regions.US_WEST_2));
CognitoUserPool userPool = new CognitoUserPool(getApplicationContext(), "us-west-2_ghtcc6ho9", "4t0mk45hNso69dp2j4jvel5ghm", "1jmq0lhhq721oif9k6nug31c29i760vihua8hvrgu5umfr2a1vd7", identityProviderClient);
cogUser = userPool.getUser();
authenticationHandler = new AuthenticationHandler() {
#Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
String ids = userSession.getIdToken().getJWTToken();
Log.d("MyToken","session id___"+userSession.getIdToken().getExpiration()+"___"+userSession.getIdToken().getIssuedAt());
Intent pubSub = new Intent(MainActivity.this, PubSubActivity.class);
pubSub.putExtra("token",""+ids);
startActivity(pubSub);
//MainActivity.this.finish();
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
Log.d("MyToken","getAuthenticationDetails");
AuthenticationDetails authenticationDetails = new AuthenticationDetails("shone", "172737", null);
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
Log.d("MyToken","getMFACode");
multiFactorAuthenticationContinuation.continueTask();
}
#Override
public void authenticationChallenge(ChallengeContinuation continuation) {
Log.d("MyToken","authenticationChallenge"+continuation.getChallengeName());
newPasswordContinuation.continueTask();
}
#Override
public void onFailure(Exception exception) {
exception.printStackTrace();
Log.d("MyToken","onFailure");
}
};
cogUser.getSessionInBackground(authenticationHandler);
When It reaches 'OnSuccess' I am launching my connect activity and passing my session token along with the Intent. Moving to the next activity
private static final String COGNITO_POOL_ID = "us-west-2:a153a090-508c-44c0-a9dd-efd450298c4b";
private static final Regions MY_REGION = Regions.US_WEST_2;
AWSIotMqttManager mqttManager;
String clientId;
AWSCredentials awsCredentials;
CognitoCachingCredentialsProvider credentialsProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
if(null == intent){
Toast.makeText(getApplicationContext(), "Token is null", Toast.LENGTH_SHORT).show();
}else {
token = intent.getStringExtra("token");
}
clientId = UUID.randomUUID().toString();
credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
COGNITO_POOL_ID,
MY_REGION
);
mqttManager = new AWSIotMqttManager(clientId, CUSTOMER_SPECIFIC_ENDPOINT);
Map loginsMap = new HashMap();
loginsMap.put("cognito-idp.us-west-2.amazonaws.com/us-west-2_ghtcc6ho9", token);
credentialsProvider.setLogins(loginsMap);
Log.d("SESSION_ID", ""+token);
new Thread(new Runnable() {
#Override
public void run() {
credentialsProvider.refresh();
awsCredentials = credentialsProvider.getCredentials();
Log.d("SESSION_ID B: ", ""+awsCredentials.getAWSAccessKeyId());
Log.d("SESSION_ID C: ", ""+awsCredentials.getAWSSecretKey());
}
}).start();
}
View.OnClickListener connectClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "clientId = " + clientId);
try {
mqttManager.connect(credentialsProvider, new AWSIotMqttClientStatusCallback() {
#Override
public void onStatusChanged(final AWSIotMqttClientStatus status,
final Throwable throwable) {
Log.d(LOG_TAG, "Status = " + String.valueOf(status)+"______"+((null !=throwable)?throwable.getMessage():""));
runOnUiThread(new Runnable() {
#Override
public void run() {
if (status == AWSIotMqttClientStatus.Connecting) {
tvStatus.setText("Connecting...");
} else if (status == AWSIotMqttClientStatus.Connected) {
tvStatus.setText("Connected");
} else if (status == AWSIotMqttClientStatus.Reconnecting) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
}
tvStatus.setText("Reconnecting");
} else if (status == AWSIotMqttClientStatus.ConnectionLost) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
throwable.printStackTrace();
}
tvStatus.setText("Disconnected");
} else {
tvStatus.setText("Disconnected");
}
}
});
}
});
} catch (final Exception e) {
Log.e(LOG_TAG, "Connection error.", e);
}
}
};
What is wrong in my code? Why it throws exception when the MQTT connect is being invoked? Any help would be appreciated.
I beat my head up with this almost a week.
Full course of action ->
After succesfull login you will have a jwt token
String idToken = cognitoUserSession.getIdToken().getJWTToken();
put it into a map
Map<String, String> logins = new HashMap<String, String>();
//fill it with Cognito User token
logins.put("cognito-idp.<REGION>.amazonaws.com/<COGNITO_USER_POOL_ID>", idToken);
then use it to set in two places (not stated in any documentation!)
CognitoCachingCredentialsProvider credentialsProvider = new
CognitoCachingCredentialsProvider(context, IDENTITY_POOL_ID, REGION);
credentialsProvider.setLogins(logins);
and
AmazonCognitoIdentity cognitoIdentity = new AmazonCognitoIdentityClient(credentialsProvider);
GetIdRequest getIdReq = new GetIdRequest();
getIdReq.setLogins(logins); //or if you have already set provider logins just use credentialsProvider.getLogins()
getIdReq.setIdentityPoolId(COGNITO_POOL_ID);
GetIdResult getIdRes = cognitoIdentity.getId(getIdReq);
after that you still nedd to make some call
AttachPrincipalPolicyRequest attachPolicyReq = new AttachPrincipalPolicyRequest(); //in docs it called AttachPolicyRequest but it`s wrong
attachPolicyReq.setPolicyName("allAllowed"); //name of your IOTAWS policy
attachPolicyReq.setPrincipal(getIdRes.getIdentityId());
new AWSIotClient(credentialsProvider).attachPrincipalPolicy(attachPolicyReq);
and only after that you can enable connect button and continue like that
mqttManager.connect(credentialsProvider, new AWSIotMqttClientStatusCallback() {
Really for this small piece of code i spent a lot of time...
I was also getting same error -
Feb 27, 2019 10:23:09 AM com.amazonaws.services.iot.client.mqtt.AwsIotMqttConnectionListener onFailure
WARNING: Connect request failure
MqttException (0) - java.io.IOException: Already connected
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: Already connected
at java.io.PipedOutputStream.connect(PipedOutputStream.java:100)
but the problem was different.
First of all, you do not need to call attachPrincipalPolicy from code. You can use the command line as well. You can do something like -
aws iot attach-principal-policy --principal us-east-1:1c973d17-98e6-4df6-86bf-d5cedc1fbc0d --policy-name "thingpolicy" --region us-east-1 --profile osfg
You will get the principal ID from identity browser of your identity pool. Now lets come to the error -
To successfully connect to mqtt with authenticated Cognito credentials, you need 2 correct policies -
Authenticated role corresponding to your identity pool should allow all mqtt operations.
AWS IoT policy should allow the same operations and you need to associate your cognito identity with this policy. We use attachPrincipalPolicy to do so.
If anyone step is missed we get above error. I agree the error is misleading - Already connected makes no sense to me for this. I would normally think it has to do with clientId, which should be unique. But anyways hopefully AWS folks would make this better at some point.
For my particular case issue was point 1. Though my IoT policy had all the required permissions, the auth role corresponding to the identity pool did not. So make sure you do that.
I have created a youtube video to show this as well: https://www.youtube.com/watch?v=j2KJVHGHaFc
When a client connected to broker it has a unique client ID. If clients tried to connect with same client id then this error occur. Use different client IDs like foo1, foo2, foo3, etc.

Wi-Fi Direct between android and Linux

I have a little problem to connect a linux with Android using Wi-Fi Direct.
On my Linux : I use :
p2p_find
p2p_peers
p2p_prov_disc <ANDROID:MAC> keypad
I got the response :
P2P-PROV-DISC-SHOW-PIN 96:35:0a:d5:83:e8 44779443
On Android I use this code :
bsend.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
System.out.println("Click Connection :");
WifiP2pConfig config = new WifiP2pConfig();
if (peers.size() == 0)
{
System.out.println("No peers found , MAC test : 00:e0:4c:61:0f:d0");
config.deviceAddress = "00:e0:4c:61:0f:d0";
}
else
{
WifiP2pDevice device = (WifiP2pDevice) peers.get(0);
config.deviceAddress = device.deviceAddress;
System.out.println("Connection to: " + config.deviceAddress);
}
config.wps.setup = WpsInfo.DISPLAY;
config.wps.pin = pin.getText().toString();
config.groupOwnerIntent = 0;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
System.out.println("Connection Suceess");
}
#Override
public void onFailure(int i) {
Toast.makeText(MainActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
System.out.println(i);
System.out.println("Connection failed");
}
});
}
});
On my Logcat I got :
Click Connection :
code :44779443
Connection to: 00:e0:4c:61:0f:d0
2
Connection failed
ifconfig on my Linux :HWaddr 00:e0:4c:61:0f:d0
I am new with Android, I don't know if can't print a "errno" coresponding to my failure code. And I dont see in the class WifiP2pManager an interface for a callback function failure connection.
Edit: I also tried config.wps.setup = WpsInfo.KEYPAD; and I think it's more accurate.
Edit:I'm stupid, that worked fine, it's just i push twice the connect button (yeah I thought I mistaken somewhere with event managament).
So i used PBC method now :
config.wps.setup = WpsInfo.PBC;
config.groupOwnerIntent = 0;
After that I created a Socket :
new Thread(new Runnable() {
#Override
public void run() {
try {
Socket socket = new Socket("192.168.0.1", 4242);
if (socket.isConnected())
{
System.out.println("Connection ok");
}
else
System.out.println("connection failed");
}catch (IOException e)
{
System.out.println(e);
}
}
}).start();
But I got :java.net.ConnectException: failed to connect to /192.168.0.1 (port 4242): connect failed: ENETUNREACH (Network is unreachable)
Why on my c program basically i made :
-> connection to wpa_supplicant using wpa_ctrl.c
-> PING REQUEST to wpa_supplicant, reponse : PONG
-> P2p find
-> socket, bind , listen... No error return
-> p2p peer FIRST ( i dont manage all device for now)
-> p2p_prov_disc MAC::address pbc
-> using Select for checking Connection for accept
If I got a connection Success why I got Network unreachable?
And when I click to connect I go in the callack function OnpeersAvailable and no in OnConnectionInfoAvailable...

SignalR HTTP status 400 multiple clients

I'm running an application with SignalR 2.2.0 on server side and signalr-java-client (self compiled, last GitHub version) on Android as client.
Currently, there are 4 clients connected to my hub. From time to time, it happens, that all 4 clients simultaneously receive the HTTP status 400 with the message "The connection id is in the incorrect format" (the clients were connected before). I analyzed this multiple times and am not able to find any information/pattern when or why this happens.
The connecten is secured via JWT, the token is definitely valid. When retrieving a new token, the connection is stopped and started again. Apart from this, it is very unlikely that the error is device-related, because the error is thrown at all 4 clients the same time.
I know, this error can occur when the client's Identity changes, but an Identity change for 4 clients the same time seems very unlikely to me.
This is the server-code used for authentication (Deepak asked).
The following method gets called in my Startup.cs:
public static void ConfigureOAuth(IAppBuilder app, string audienceID, string sharedSecret)
{
byte[] secret = TextEncodings.Base64Url.Decode(sharedSecret);
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
Provider = new MyOAuthBearerAuthenticationProvider(),
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceID },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(Issuer, secret)
}
});
}
Here's the code of MyOAuthBearerAuthenticationProvider class:
class MyOAuthBearerAuthenticationProvider : OAuthBearerAuthenticationProvider
{
/// <summary>
/// Get's a JWT from querysting and puts it to context
/// </summary>
public override Task RequestToken(OAuthRequestTokenContext context)
{
if (context.Token == null)
{
string value = context.Request.Query.Get("auth_token");
if (!string.IsNullOrEmpty(value)) //token from queryString
{
context.Token = value;
}
}
return Task.FromResult<object>(null);
}
}
I have to retrieve the token from query string, because additionally to the java-client, a javascript client is used, which is not able to set headers.
Lastly, I secure my hub and some of it's methods with the Authorization attribute:
[Authorize(Roles = "MyExampleRole")]
This is the client-code for connection:
public boolean connect(String url, String token) {
if (connected) {
return true;
}
try {
this.hubConnection = new HubConnection(url, "auth_token=" + token, true, logger);
this.hubProxy = hubConnection.createHubProxy("MyHub");
this.hubProxy.subscribe(this.signalRMethodProvider);
this.hubConnection.stateChanged(stateChangedCallback);
SignalRFuture<Void> awaitConnection = this.hubConnection.start();
awaitConnection.get(10000, TimeUnit.MILLISECONDS);
return true;
}
catch (InterruptedException | TimeoutException | ExecutionException e) {
log.error("connect", e);
return false;
}
}
Does anybody have an Idea, how to fix this problem or where I may receive further information?
Thank you very much
-Lukas
seems fine...
possible alteration you can do is change
awaitConnection.get(10000, TimeUnit.MILLISECONDS);
to
awaitConnection.done(new Action<Void>() {
#Override
public void run(Void obj) throws Exception {
Log.d(TAG, "Hub Connected");
}
}).onError(new ErrorCallback() {
#Override
public void onError(Throwable error) {
error.printStackTrace();
Log.d(TAG, "SignalRServiceHub Cancelled");
}
}).onCancelled(new Runnable() {
#Override
public void run() {
Log.d(TAG, "SignalRServiceHub Cancelled");
}
});

How to connect Android on RabbitMQ?

I'd like to use RabbitMQ client from an android App.
From the server side, i use SpringBoot with spring AMQP. RabbitMQ (rabbitmq_server-3.4.3) is installed correctly and an integration test valid the server behaviour.
The difficult part is when i try to create a connection from RabbitMQ connectionFactory inside my android project.
I get this exception :
failed to connect to localhost/127.0.0.1 (port 5672):
connect failed: ECONNREFUSED (Connection refused)
In android manifest, Internet permission is set :
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Here is my code :
public class LoadingTask extends AsyncTask<String, Integer, Integer> {
private static String replyQueue = "REPLY_QUEUE";
public interface LoadingTaskListener {
void onResourceLoaded();
}
private final ProgressBar progressBar;
private final LoadingTaskListener loadingTaskListener;
private ConnectionFactory connectionFactory;
public LoadingTask(ProgressBar progressBar, LoadingTaskListener loadingTaskListener) {
this.progressBar = progressBar;
this.loadingTaskListener = loadingTaskListener;
this.connectionFactory = new ConnectionFactory();
connectionFactory.setAutomaticRecoveryEnabled(true);
}
#Override
protected Integer doInBackground(String... params) {
try {
/*init rabbitMQ Context*/
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
channel.basicQos(1);
channel.queueDeclare(DATA_QUEUE.getName(), false, false, false, null);
AMQP.Queue.DeclareOk q = channel.queueDeclare();
channel.queueBind(q.getQueue(), "amq.fanout", "chat");
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(replyQueue, true, consumer);
/* initiate RPC */
String corrId = java.util.UUID.randomUUID().toString();
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
.correlationId(corrId)
.replyTo(replyQueue)
.build();
AmqpRequest request = new AmqpRequest(LIST_IMAGE);
Gson gson = new Gson();
String jsonRequest = gson.toJson(request);
channel.basicPublish(MAIN_EXCHANGE.getName(), DATA_QUEUE.getRoutingKey(), props, jsonRequest.getBytes());
String response;
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
if (delivery.getProperties().getCorrelationId().equals(corrId)) {
response = new String(delivery.getBody());
break;
}
}
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Dummy Data until i can't connect to rabbitMQ
return 1234;
}
}
Is it really possible to connect Android on RabbitMQ, or should i use a kind of http bridge ?
Could anyone provide me an exemple for both http bridge or RabbitMQ connection.
Thank you

Using Netty ( tcp ), sending message from client in android to server

I successed connection bitween client in android and server.
but, when I want to send message like "hello" or whatever, message was disappear.
this is my client code:
group = new OioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(OioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(handler);
}
});
Channel ch = null;
ChannelFuture f = null;
try {
f = b.connect(new InetSocketAddress(host, port)).sync();
ch = f.channel();
} catch (InterruptedException e) {
e.printStackTrace();
}
ch.writeAndFlush("hello!");
and this is my server code:
#Override
public void channelActive(ChannelHandlerContext ctx){
channels.add(ctx.channel());
ctx.channel().writeAndFlush("Welcome My Server");
System.out.println(ctx.channel().remoteAddress());
}
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
try {
while (in.isReadable()) {
System.out.print((char) in.readByte());
System.out.flush();
}
} finally {
ReferenceCountUtil.release(msg);
}
}
when I connect, Server was printing 'connected client ip address'
but after that, 'hello' message is not printed in my server.
what is wrong? server? client?
I think encode, decode is not problem, cuz nothing received
please let me know how to do for that?
If you want to write a String you need to put StringEncoder in the ChannelPipeline (on the client side). If you check the returned ChannelFuture of writeAndFlush(...) you will see it was failed.

Categories

Resources