Cannot connect to node websocket from android okhttp3 - android

I've created a node server on top of expressJs and used socket.io to create a websocket server. Code i've used to create the server is
io.sockets.on('connection', function (socket) {
connections.push(socket);
console.log('Connected: ' + connections.length + 'sockets connected');
io.sockets.emit('connected', JSON.stringify({status: "online"}));
socket.on('disconnect', function (data) {
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: ' + connections.length + ' sockets connected');
io.sockets.emit('disconnected', {status: "offline"});
});
socket.on('request', function (data) {
console.log('new request in server: ' + data.toString());
io.sockets.emit('newRequest', JSON.stringify({request: data}));
})
});
I can connect with the server from any browser including mobile and emulator browser, But i failed to connect using okhttp3 websocket.
I am following https://gist.github.com/AliYusuf95/557af8be5f360c95fdf029795291eddb this gist to create the client. but i failed to connect with the websocket. I'm getting the following error
D/OkHttp: <-- HTTP FAILED: java.io.IOException: unexpected end of stream on Connection{192.***.0.***:3000, proxy=DIRECT# hostAddress=/192.***.0.***:3000:3000 cipherSuite=none protocol=http/1.1}
What's going wrong?

Try the following...see if that works.
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://websockethost:8080");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
#Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView)findViewById(R.id.messages);
textView.setText(textView.getText() + "\n" + message);
}
});
}
#Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
Source

Related

SignalR negotiate method calling in loop sometimes in 24 hours

I have used below code to connect with hub.
Its working proper. but sometime suddenly the negotiate GET method calls thousands of time.
private HubConnection createLocalHubConnection() {
if (Common.isInternetAvailable(CallObserverTestService.this)) {
Log.i(TAG, "Create Connection");
final HubConnection loConnection = new HubConnection(WebService.getHubURL(CallObserverTestService.this));
Log.i(TAG, "Connection State1: " + loConnection.getState());
if (loConnection.getState() == ConnectionState.Disconnected) {
moProxy = loConnection.createHubProxy(CallObserverTestService.this.getString(R.string.hub));
try {
loConnection.stop();
loConnection.start().done(new Action<Void>() {
#Override
public void run(Void obj) throws Exception {
Log.i(TAG, "Connection URL: " + loConnection.getUrl());
Log.i(TAG, "SignalR ConnectionId: " + loConnection.getConnectionId());
}
}).onError(new ErrorCallback() {
#Override
public void onError(Throwable error) {
Log.i(TAG, "SignalR: onError : " + error.getMessage());
error.printStackTrace();
Log.logException(TAG, error);
}
});
} catch (Exception e) {
e.printStackTrace();
Log.logException(TAG, e);
}
}
return loConnection;
}
return null;
}
The error is as below while calling in loop
Negotiation error: There was a problem in the negotiation with the
server
negotiate: https://MyDomain/signalr/negotiate?clientProtocol=1.3&connectionData=%5B%7B%22name%22%3A%22MyHubName%22%7D%5D
Reference link: https://github.com/SignalR/java-client/tree/master/signalr-client-sdk

Android: Quickblox Client is not, or no longer, connected. error

I use Quickblox for chat room
My code:
final QBChatDialog dialog = DialogUtils.buildPrivateDialog(id);
dialog.setType(QBDialogType.PRIVATE);
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog result, Bundle params) {
try {
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody("Hi there!");
dialog.sendMessage(chatMessage);
} catch (SmackException.NotConnectedException e) {
Log.i("errorCheck", "Chat: NO : " + e.getMessage());
}
}
#Override
public void onError(QBResponseException responseException) {
Log.i("errorCheck", "Chat: FAIL" + responseException.getMessage());
}
});
I get this error :
Client is not, or no longer, connected. error
But I'm sure my client is connected
You need to do the following before sending message:
qbChatDialog.initForChat(QBChatService.getInstance());

Add topic/subscription after stomp client is connected

I am currently using
https://github.com/NaikSoftware/StompProtocolAndroid
to connect websocket using STOMP. I have a simple implementation as
public class TestActivity extends AppCompatActivity {
private StompClient mStompCLient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
mStompCLient = Stomp.over(WebSocket.class, BASE_URL);
mStompCLient.topic("/topic/online/" + mSharedPreferences.getPrivateKey()).subscribe(new Subscriber<StompMessage>() {
#Override
public void onCompleted() {
Log.i(TAG, "/topic/online/ onCompleted: ");
}
#Override
public void onError(Throwable e) {
Log.i(TAG, "/topic/online/ onError: " + e.getMessage());
}
#Override
public void onNext(StompMessage stompMessage) {
Log.d(TAG, "/topic/online/ onNext: " + stompMessage.getPayload());
String content = "";
JSONObject jsonResponse = null;
try {
jsonResponse = new JSONObject(stompMessage.getPayload());
content = jsonResponse.getString("uri");
} catch (JSONException e) {
e.printStackTrace();
}
listenToUpdatesFromFinalUri(content);
}
});
mStompCLient.lifecycle().subscribe(lifecycleEvent -> {
Log.i(TAG, "onCreate: " + lifecycleEvent.getMessage());
switch (lifecycleEvent.getType()) {
case OPENED:
Log.d(TAG, "Stomp connection opened");
break;
case ERROR:
Log.e(TAG, "Error", lifecycleEvent.getException());
break;
case CLOSED:
Log.d(TAG, "Stomp connection closed : " + lifecycleEvent.toString() + " :msg: " + lifecycleEvent.getMessage() + " :escep: " + lifecycleEvent.getException() + " :headers: " + lifecycleEvent.getHandshakeResponseHeaders() + " :type: " + lifecycleEvent.getType());
break;
}
});
mStompCLient.connect();
}
private void listenToUpdatesFromFinalUri(String content) {
mStompCLient.topic(content).subscribe(new Subscriber<StompMessage>() {
#Override
public void onCompleted() {
Log.i(TAG," onCompleted: ");
}
#Override
public void onError(Throwable e) {
Log.i(TAG, " onError: " + e.getMessage());
}
#Override
public void onNext(StompMessage stompMessage) {
Log.d(TAG, " onNext: " + stompMessage.getPayload());
}
});
}
#Override
protected void onStop() {
super.onStop();
disconnectStomp();
}
private void disconnectStomp() {
mStompCLient.disconnect();
}
}
Here I am trying to listen to the new subscription channel sent by the server after connection is established. It works if the subscribe() is called before the connect is called. But the final uri/subscription channel subscribed in listenToUpdatesFromFinalUri() function is not static so I need can't add subscription before the connect. I am currently unable to get response for the final uri/subscription. Any help is appreciated.
The issue has been solved in the new version 1.1.6

Why websocket from AndroidAsync always null

I'm developing a simple WebSocket in Android using AndroidAsync library:
http://www.koushikdutta.com/AndroidAsync
My Client code:
private void conectar() {
//String uri = "ws://192.167.101.142:1234";
String uri = "http://192.167.101.166:1234";
AsyncHttpClient asyncHttpClient = AsyncHttpClient.getDefaultInstance();
//asyncHttpClient.websocket(new AsyncHttpGet(uri), "my-protocol", new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(uri, "https", new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(new AsyncHttpGet(uri), null, new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(new AsyncHttpGet(uri), "SSL", new AsyncHttpClient.WebSocketConnectCallback() {
asyncHttpClient.websocket(uri, null, new AsyncHttpClient.WebSocketConnectCallback() {
#Override
public void onCompleted(Exception ex, WebSocket webSocket) {
Log.e(TAG, "webSocket is null");
Log.e(TAG, "Metodo onCompleted");
if (ex != null) {
Log.e(TAG, ex.getMessage(), ex);
return;
}
//Log.e(TAG, "webSocket.isOpen(): " + webSocket.isOpen());
webSocket.send("a string");
webSocket.send(new byte[10]);
webSocket.setStringCallback(new WebSocket.StringCallback() {
public void onStringAvailable(String s) {
System.out.println("I got a string: " + s);
Log.e(TAG, "I got a string: " + s);
//showToast("I got a string: " + s);
}
});
webSocket.setDataCallback(new DataCallback() {
#Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList byteBufferList) {
System.out.println("I got some bytes!");
Log.e(TAG, "I got some bytes!");
// note that this data has been read
byteBufferList.recycle();
}
});
}
});
}
My Server code:
private void conectar() {
AsyncHttpServer server = new AsyncHttpServer();
server.listen(PORTA);
server.get("/", new HttpServerRequestCallback() {
#Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
response.send("Hello!!!");
}
});
server.websocket("/", new AsyncHttpServer.WebSocketRequestCallback() {
#Override
public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) {
Log.e(TAG, "Metodo: onConnected");
_sockets.add(webSocket);
//Use this to clean up any references to your websocket
webSocket.setClosedCallback(new CompletedCallback() {
#Override
public void onCompleted(Exception ex) {
Log.e(TAG, "Metodo onCompleted from webSocket object");
try {
if (ex != null)
Log.e("WebSocket", "Error");
} finally {
_sockets.remove(webSocket);
}
}
});
webSocket.setStringCallback(new WebSocket.StringCallback() {
#Override
public void onStringAvailable(String s) {
Log.e(TAG, "Metodo onStringAvailable from webSocket object");
if ("Hello Server".equals(s))
webSocket.send("Welcome Client!");
}
});
}
});
Anyone knows tell me why Can't I connect my server?
I have tested the server code in another app websocket tester from google play.
The app server it's Ok.
However I cannot connect from my client app?

Using Autobahn for WebSocket comms, not receiving from Server

I'm implement Autobahn to connnect to a server through WebSockets. When I hit connect, it opens the socket correctly and logs that socket is opened. I then try to send a request to the server which is simply {"request":"getSoftwareVersion"} , when the server receives this, it should send back the software version in a JSON object, the trouble is, that onMessage is never hit. Here is my code:
public class AutoBahnConnectRequest extends Request{
private static WebSocketConnection mAutoBahnConnection;
private String mSocketHostAddress;
private final static String m_TAG = AutoBahnConnectRequest.class.getSimpleName();
public AutoBahnConnectRequest(String SocketHostAddress){
this.mAutoBahnConnection = new WebSocketConnection();
this.mSocketHostAddress = SocketHostAddress;
}
#Override
protected Void doInBackground(Void... params){
try {
mAutoBahnConnection.connect(mSocketHostAddress, new WebSocketHandler(){
#Override
public void onOpen() {
String requestSoftware = "{\"request\":\"getSoftwareVersion\"}";
Log.i(m_TAG, requestSoftware);
Log.i(m_TAG, "Status: Connected to " + mSocketHostAddress);
mAutoBahnConnection.sendTextMessage(requestSoftware);
}
#Override
public void onTextMessage(String payload) {
Log.i(m_TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.i(m_TAG, "Connection lost."+ reason);
}
});
} catch (WebSocketException e) {
Log.d(m_TAG, e.toString());
}
return null;
}
}
This has been implemented with a html client like so (not with autobahn):
function getSoftwareVersion() {
socket_di.send('{"request":"getSoftwareVersion"}');
}
and the onMessage receives the data. Can someone please tell me if I'm doing something wrong here?
Thank you.
I have figured out my issue regarding this. The WebSocket connection required a protocol and options to be added. So I changed this:
mAutoBahnConnection.connect(mSocketHostAddress, new WebSocketHandler(){
#Override
public void onOpen() {
String requestSoftware = "{\"request\":\"getSoftwareVersion\"}";
Log.i(m_TAG, requestSoftware);
Log.i(m_TAG, "Status: Connected to " + mSocketHostAddress);
mAutoBahnConnection.sendTextMessage(requestSoftware);
}
#Override
public void onTextMessage(String payload) {
Log.i(m_TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.i(m_TAG, "Connection lost."+ reason);
}
});
} catch (WebSocketException e) {
Log.d(m_TAG, e.toString());
}
to this:
mAutoBahnConnection.connect(mSocketHostAddress,new String[]{"this is my protocol"} ,new WebSocketHandler(){
#Override
public void onOpen() {
String requestSoftware = "{\"request\":\"getSoftwareVersion\"}";
Log.i(m_TAG, requestSoftware);
Log.i(m_TAG, "Status: Connected to " + mSocketHostAddress);
mAutoBahnConnection.sendTextMessage(requestSoftware);
}
#Override
public void onTextMessage(String payload) {
Log.i(m_TAG, "Got echo: " + payload);
}
#Override
public void onRawTextMessage(byte[] payload) {
try {
rawText = new String(payload, "UTF-8");
Log.i(m_TAG, "ON RAW TEXT");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onBinaryMessage(byte[] payload) {
Log.i(m_TAG, "ON BINARY MESSAGE");
}
#Override
public void onClose(int code, String reason) {
Log.i(m_TAG, "Connection lost."+ reason);
}
}, options);
} catch (WebSocketException e) {
Log.d(m_TAG, e.toString());
}

Categories

Resources