Now i'm try to connect with other device using samsung S6 Lite. Here i have a problem while connecting to the other device it's trying to connect and after few second it's OnClose method will call in my web socket listener.
I have tried on same thing in Samsung S7, Samsung S5 and emulator it's working fine. Only i got the connection issue in Samsung S6(OS: Android 11).
Node.js
const http = require('http');
const WebSocketServer = require('websocket').server;
const server = http.createServer();
server.listen(8080);
const wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
const connection = request.accept(null, request.origin);
console.log('Server Connected')
connection.on('message', function(message) {
console.log('Received Message:', message.utf8Data);
//connection.sendUTF('Hi this is WebSocket server!');
connection.sendUTF('Socket server conne');
});
connection.on('close', function(reasonCode, description) {
console.log('Client has disconnected.',description.utf8Data);
});
connection.on('error', function(error){
console.log('Client has error',error.utf8Data);
});
connection.on('frame', function(frame){
console.log('Client has frame');
});
});
wsServer.on('connect',function(connection){
console.log('Server connection status: ');
connection.on('message', function(message){
console.log('Server Received Message:', message.utf8Data);
});
});
Android Connection Code:
public void test() {
try {
URI uri;
try {
uri = new URI("ws://localhost:8080/test");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
String myAndroidDeviceId = Settings.Secure.getString(getApplicationContext().getContentResolver(), ANDROID_ID);
Map<String, String> stringStringMap = new HashMap<>();
stringStringMap.put("device", "device," + myAndroidDeviceId);
String temp[] = {"device:device"};
cc = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
String str = android.os.Build.MODEL;
String record = "Device Name : " + str;
// cc.send(String.valueOf(record));
cc.send(record);
System.out.println("Address" + cc.getRemoteSocketAddress());
Log.i("Websocket", "Opened");
System.out.println("SocketIPAddress--->Opened--->");
}
#Override
public void onMessage(String s) {
final String message = s;
System.out.println(message);
System.out.println("SocketIPAddress--->onMessage--->" + s);
updateUI(message);
}
#Override
public void onClose(int i, String s, boolean b) {
// Log.i("Websocket", "Closed " + s);
System.out.println("SocketIPAddress--->onClose--->" + s);
//updateUI("Disconnected");
}
#Override
public void onError(final Exception e) {
System.out.println("SocketIPAddress--->onError--->" + e.getMessage());
}
};
cc.connect();
} catch (Exception ex) {
Log.i("ErrorMsg", ex.getMessage());
}
}
Any one please help to fix this issue. Thanks
Related
I want to connect SignalR android client with server. I have search too much but cant get solution of my problem i am new to signalR so please anyone tell me the solution. I am getting following exception
java.util.concurrent.ExecutionException: microsoft.aspnet.signalr.client.transport.NegotiationException: There was a problem in the negotiation with the server
Here is my code
Server Side
aspx file
var IWannaChat = $.connection.myChatHub;
$.connection.hub.start().done(function () {
console.log("id : %o", $.connection.hub.id);
document.getElementById("connectionid").innerHTML =
"Name: " + $('#displayname').val() +
"<br/> Connection ID: " + $.connection.hub.id;
}
.cs file
[HubName("myChatHub")]
public class LetsChat : Hub
{
public override Task OnConnected()
{
System.Diagnostics.Debug.WriteLine("Connected");
return base.OnConnected();
}
public override Task OnDisconnected()
{
System.Diagnostics.Debug.WriteLine("Disconnected");
return base.OnDisconnected();
}
Android code
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String serverUrl = "http://192.168.100.72/Chat.aspx";
mHubConnection = new HubConnection(serverUrl);
String SERVER_HUB_CHAT = "myChatHub";
mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException | ExecutionException e) {
Log.e("SimpleSignalR Exception", e.toString());
return;
}
mHubConnection.connected(new Runnable() {
#Override
public void run() {
Global.displayLog("SignalR_connection Connected connection_Id " + mHubConnection.getConnectionId() + " ConnectionToken" +
mHubConnection.getConnectionToken());
// Toast.makeText(SignalRService.this,"Connected",Toast.LENGTH_SHORT).show();
}
});
Please help me what i am doing wrong on both sides
I am trying to implement pusher chat in my Android Application, i am able to connect with pusher, got the response as CONNECTED. But not able to connect to Private channels(Local server). Can anyone help on this.
adding the code below.
Thanks in advance
final HttpAuthorizer authorizer = new HttpAuthorizer(myurl);
authorizer.setHeaders(getMapAuthorizationHeaders());
PusherOptions options = new PusherOptions().setAuthorizer(authorizer);
final Pusher pusher = new Pusher("pusher_key", options);
pusher.connect(new com.pusher.client.connection.ConnectionEventListener() {
#Override
public void onConnectionStateChange(ConnectionStateChange connectionStateChange) {
Log.e("connectionStateChange" , connectionStateChange.getCurrentState().toString());
if (connectionStateChange.getCurrentState() == ConnectionState.CONNECTED) {
SOCKET_ID = pusher.getConnection().getSocketId();
Log.e("SOCKET_ID" , ""+SOCKET_ID);
Channel channel = pusher.subscribePrivate(PUSH_CHANNEL, new PrivateChannelEventListener() {
#Override
public void onAuthenticationFailure(String s, Exception e) {
Log.e("PUSHER", "Channel subscription authorization failed");
}
#Override
public void onSubscriptionSucceeded(String s) {
Log.e("PUSHER", "Channel subscription authorization succeeded");
}
#Override
public void onEvent(String s, String s2, String s3) {
Log.e("PUSHER", "An event with name " + s2 + " was delivered!!");
}
}, "my-event");
}
}
#Override
public void onError(String s, String s1, Exception e) {
}
});
public static HashMap<String, String> getMapAuthorizationHeaders() {
try {
HashMap<String, String> authHeader = new HashMap<>();
authHeader.put("HeaderKey1", "HeaderValue1");
authHeader.put("HeaderKey2", "HeaderValue2");
return authHeader;
} catch (Exception e) {
return null;
}
}
Can I assume that where you've put "pusher_key", you've just added this for security purposes on here, and in your application you're actually using your key?
Other than that, where are you defining PUSH_CHANNEL for: pusher.subscribePrivate(PUSH_CHANNEL,
I have made a demo for sending image to private chat using QuickBlox, I am struggling to attach an image with the chat message, I have gone through its document and have used the below Links, with no luck
Attach an image
My code is as below:
chatMessage = new QBChatMessage();
sendButton = (Button) findViewById(R.id.chatSendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String messageText = messageEditText.getText().toString();
if (TextUtils.isEmpty(messageText)) {
return;
}
// Send chat message
//
// send a message
// ...
int fileId = R.raw.ic_launcher;
InputStream is = ChatActivity.this.getResources()
.openRawResource(fileId);
File file = FileHelper.getFileInputStream(is,
"sample_file.png", "myFile");
Boolean fileIsPublic = true;
QBContent.uploadFileTask(file, fileIsPublic, messageText,
new QBEntityCallbackImpl<QBFile>() {
#Override
public void onSuccess(QBFile qbFile, Bundle params) {
String publicUrl = qbFile.getPublicUrl();
System.out
.println("==========image uploaded success++++++++"
+ publicUrl);
id = qbFile.getId();
System.out
.println("===================image id+++++++++++"
+ id + "");
}
#Override
public void onError(List<String> errors) {
System.out
.println("==========image uploaded Errors++++++++"
+ errors.toString());
}
}, new QBProgressCallback() {
#Override
public void onProgressUpdate(int progress) {
}
});
QBAttachment atach = new QBAttachment("image");
atach.setId(id+"");
ArrayList<QBAttachment> aryatch = new ArrayList<QBAttachment>();
aryatch.add(atach);
chatMessage.setAttachments(aryatch);
chatMessage.setBody(messageText);
chatMessage.setProperty(PROPERTY_SAVE_TO_HISTORY, "1");
chatMessage.setDateSent(new Date().getTime() / 1000);
try {
chat.sendMessage(chatMessage);
} catch (XMPPException e) {
Log.e(TAG, "failed to send a message", e);
} catch (SmackException sme) {
Log.e(TAG, "failed to send a message", sme);
}
messageEditText.setText("");
if (dialog.getType() == QBDialogType.PRIVATE) {
showMessage(chatMessage);
}
}
});
Well it clear where the mistake is
your id is null here
atach.setId(id+"");
because it will != nil only in onSuccess block of uploadFileTask
So the right way is to forward all attachments logic inside onSuccess block of uploadFileTask
Because these QuickBlox request are asynchronous
I am working on Autobahn Web socket communication. There is a carousel view in my application, and there are four images. When users click on of the images, then connects to server with websocket and send message. But the problem is that when I select the images, it connects to server correctly, but client(android device) connects to the websocket every single time when the message is sent.
Here is my code..
if (pos == 0) {
product_photo.setImageResource(R.drawable.myoffers_0);
product_photo.setOnClickListener(new ImageButton.OnClickListener(){
public void onClick(View v){
String id = "Product0";
Log.d(TAG, "Current product is : " + id);
A.sendMessage(id);
}
});
}
Websocket.class
public class WebSocket_Connector extends Activity{
private static final String TAG = "ECHOCLIENT";
private static final String TAG1 = "My app";
public final WebSocketConnection mConnection = new WebSocketConnection();
private String tmpString = "";
public void connect(final String wsuri) {
Log.d(TAG, "Connecting to: " + wsuri);
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri );
Log.d(TAG, "Connection successful!\n");
mConnection.sendTextMessage(tmpString);
tmpString = "";
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection closed.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
}
public void sendMessage(String message) {
if (mConnection.isConnected()) {
Log.d(TAG1, "Messeage is sent : " + message);
mConnection.sendTextMessage(message);
}
else {
tmpString = message;
connect("ws://xxx.xxx.x.xxx:xxxx");
}
}
}
It doens't go to 'if (mConnection.isConnected())' here..always goes to else.
EDIT:
I want to implement a quiz-application on Android and Browser via Web Interface.
I'm looking for a way to communicate between the server and the clients. I tried socket.io but couldn't get it working with android.
I'm using a node.js server hosted on nodester (nodester.com).
I tried some libs but couldn't get it working.
I'm now working with einaros/ws from https://github.com/einaros/ws
The server code is:
var clients = [],
numClients = 0;
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 20083});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log(wss.clients);
console.log('received: %s', message);
incomingMessage(message, ws)
});
/*
ws.on('eigenesEvent', function(message) {
console.log('eigenes Event ausgelöst: ' + message);
});
*/
});
function incomingMessage(msg, ws) {
//console.log(wss.clients);
var obj = JSON.parse(msg);
if(obj.type == "connect") {
for(var i=0;i<clients.length;i++) {
if(clients[i] == obj.id) {
ws.send(JSON.stringify({
to: obj.id,
message: "name vergeben"
}));
return;
}
}
clients[numClients] = obj.id;
numClients++;
for(var i=0;i<clients.length;i++) {
console.log("Client" + i + ": " + clients[i]);
}
ws.send(JSON.stringify({
to: "all",
message: obj.id + " connected"
}));
}
if(obj.type == "disconnect") {
for(var i=0;i<clients.length;i++) {
if(clients[i] == obj.id) {
clients.splice(i, 1);
numClients--;
for(var i=0;i<clients.length;i++) {
console.log("Client" + i + ": " + clients[i]);
}
}
}
ws.send(JSON.stringify({
to: "all",
message: obj.id + " disconnected"
}));
return;
}
if(obj.type == "answer") {
if("id" in obj) {
if(obj.answer == "a") {
ws.send(JSON.stringify({
to: obj.id,
message: "a is correct"
}));
} else {
ws.send(JSON.stringify({
to: obj.id,
message: "answer is incorrect"
}));
}
}
}
if(obj.type == "something") {
if("id" in obj) {
ws.send(JSON.stringify({
to: obj.id,
message: "received: " + obj.message
}));
}
}
}
From a HTML-Site i can connect to the server via:
connect = function() {
var host = "ws://einaros.nodester.com";
try{
socket = new WebSocket(host);
console.log('WebSocket - status ' + socket.readyState);
socket.onopen = function(msg) {
console.log("Welcome - status " + this.readyState);
socket.send(JSON.stringify({
id: model.getClientName(),
type: "connect"
}));
model.setConnectionStatus(true);
};
socket.onmessage = function(msg) {
console.log("onmessage - msg: " + msg.data);
checkMessage(msg.data);
};
socket.onclose = function(msg) {
console.log("Disconnected - status " + this.readyState);
model.setConnectionStatus(false);
};
}
catch(ex){
console.log(ex);
}
},
On the Android-Client side i'm using AutobahnAndroid from: http://autobahn.ws/android
The client code for android is:
package ps.mediengestaltung;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;
public class MainActivity extends Activity {
public final WebSocketConnection mConnection = new WebSocketConnection();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String wsuri = "ws://einaros.nodester.com";
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d("TAG", "Status: Connected to " + wsuri);
mConnection.sendTextMessage("Hello Server!");
}
#Override
public void onTextMessage(String payload) {
Log.d("TAG", "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d("TAG", "Connection lost.");
}
});
} catch (WebSocketException e) {
Log.d("TAG", e.toString());
}
}
}
In LogCat i get:
08-01 08:48:13.017: D/TAG(704): Status: Connected to ws://einaros.nodester.com
08-01 08:48:13.167: D/TAG(704): Connection lost.
What am i doing wrong? Any hints?
The reason could be: Weberknecht only implements the (outdated) Hixie-76 version of WebSocket.
You might try AutobahnAndroid, which implements the final RFC6455 version of WebSocket.
Another things: the WebSocket server you are using is no longer maintained (as far as I know). It also only implements Hixie-76 - which is no longer supported by Chrome/Firefox.
Try one of these:
https://github.com/einaros/ws
https://github.com/Worlize/WebSocket-Node
Disclaimer: I am the author of Autobahn and work for Tavendo.
You are asking your phone to connect to the localhost. You aren't running node on the phone right? :)
URI url = new URI("ws://127.0.0.1:8080/test");
This should instead be pointing to your nodester address/port.