Unable to connect android signalr with server - android

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

Related

How to accept an incoming audio SIP call using JAIN SIP Library?

It is my first time creating working with JAIN SIP. I have created Android SIP Client using JAIN SIP. I am able to get a notification of an incoming call and receive it but am not able to get the audio stream working. I guess the problem might be the way define the Session Description Protocol(SDP) for an audio stream.
Below is my acceptCall method:
public void acceptCall() throws IllegalStateException {
soundManager.setupAudioStream();
Request request = incomingRequest.getRequest();
remoteIP = SDPBuilder.getRemoteIP(incomingRequest.getRequest());
try {
Response response = messageFactory.createResponse(Response.OK, request);
response.addHeader(localContactHeader);
ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("application", "sdp");
response.setContent(getSDPData().getBytes(), contentTypeHeader);
SipResponder responder = new SipResponder(sipProvider, incomingRequest, currentServerTransaction);
responder.execute(response);
} catch (Exception e) {
if (BuildConfig.DEBUG) e.printStackTrace();
direction = CallDirection.NONE;
notifySessionFailed("couldn't establish call");
}
}
Here is my method that returns SDP Data:
private String getSDPData()
{
return "v=0\r\n"
+ "o=4855 13760799956958020 13760799956958020"
+ " IN IP4 " + localIP + "\r\n"
+ "s=mysession session\r\n"
+ "c=IN IP4 "
+ localIP + "\r\n" + "t=0 0\r\n"
+ "m=audio " + String.valueOf(port)
+ " RTP/AVP 0 4 18\r\n"
+ "a=rtpmap:0 PCMU/8000\r\n"
+ "a=rtpmap:4 G723/8000\r\n"
+ "a=rtpmap:18 G729A/8000\r\n" + "a=ptime:20\r\n";
}
Lastly my SIP Responder class:
public class SipResponder extends AsyncTask<Response, String, ServerTransaction> {
private static final String TAG = "BACKGROUND";
private SipProvider sipProvider;
private RequestEvent requestEvent;
private ServerTransaction transaction;
public SipResponder(SipProvider provider, RequestEvent event, ServerTransaction transaction) {
sipProvider = provider;
requestEvent = event;
this.transaction = transaction;
}
#Override
protected ServerTransaction doInBackground(Response... responses) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Request request = requestEvent.getRequest();
Response response = responses[0];
try {
if (transaction == null)
transaction = requestEvent.getServerTransaction();
if (transaction == null) {
transaction = sipProvider.getNewServerTransaction(request);
}
transaction.sendResponse(response);
return transaction;
} catch (TransactionAlreadyExistsException e) {
Log.e(TAG, "that race condition. UGH");
e.printStackTrace();
return null;
} catch (Exception e) {
Log.e(TAG, "the response failed. UGH");
e.printStackTrace();
return null;
}
}}
It has been a struggle for a while now. Kindly help.

how to display data received from android client in server.js to html file?

I wrote this node.js server which receives data from android client .But i tried to display the data in html page i could not display and i don't have any idea how to display in html page since am a beginner in nodejs. I just started to explore to get count of active users in realtime.
my nodejs server.js code
var net = require('net');
var sockets = [];
var connectCounter=0;
var svr = net.createServer()
svr.on("connection",function(sock) {
connectCounter++;
var remoteAddress = sock.remoteAddress + ":" + sock.remotePort;
console.log("new client connection is made %s", remoteAddress);
sockets.push(sock);
sock.write('Welcome to the server!\n');
sock.on('data', function(data) {
console.log("Data from %s :%s", remoteAddress, data);
sock.write("Hello", + data);
console.log("connection_id:", + sock.id);
console.log("Number of active state(connection) :",connectCounter);
});
sock.on('end', function() {
connectCounter--;
console.log('Disconnected: ' + sock.remoteAddress + ':' + sock.remotePort);
console.log("Number of active state(disconnected) :",connectCounter);
var idx = sockets.indexOf(sock);
if (idx != -1) {
delete sockets[idx];
}
});
});
var svraddr = 'localhost';
var svrport = 3000;
svr.listen(svrport, svraddr);
console.log('Server Created at ' + svraddr + ':' + svrport + '\n');
My android code
socket = new Client("localhost", 3000);
socket.setClientCallback(new Client.ClientCallback() {
#Override
public void onMessage(String message) {
System.out.println("Socket_connection_msg" + message);
}
#Override
public void onConnect(Socket sockett) {
try {
JSONObject jsonObject=new JSONObject();
jsonObject.put("name" ,"MainActivity");
jsonObject.put("value" ,"45");
socket.send(jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Socket_connection" + sockett.isConnected());
//socket.disconnect();
}
#Override
public void onDisconnect(Socket socket, String message) {
System.out.println("Socket_connection_disconnect" + socket.isConnected()+ message);
}
#Override
public void onConnectError(Socket socket, String message) {
System.out.println("Socket_connection_error" + message);
}
});
socket.connect();
My console output is
When a new android device is connected active state increases and if user goes out of app it disconnects and connection gets decremented by 1.
Now i need the response to displayed in HTML page
I am new to nodejs , any help would be appreciated
Thank you in advance.

Sending Email in Android using JavaMail API without using mailing APP

Sending Email in Android using JavaMail API without using the default/built-in app
Using this tutorial, I've loaded up the code into a sample android project and imported the libraries. Changed the parameters in the lines:
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
GMailSender sender = new GMailSender("sender#gmail.com", "sender_password");
sender.sendMail("This is Subject", "This is Body", "sender#gmail.com", "recipient#gmail.com");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
Wanted to test it out and in this code, the try block of code gets executed successfully when I press the button, but I don't receive the mail, nor do I get any errors. Since there's no readme or any guidelines as to how to use this code, I have no choice but to ask what I'm doing wrong.
Just to clear the confusion, I've put the senders email instead of sender#gmail.com, same goes for password and recipient#gmail.com.
I've also added the INTERNET permission to the manifest.
If you want to use mailgun instead you can do it like this:
public void sendEmailInBackground(final String subject, final String body, final String... toAddress) {
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
String hostname = "smpt.mailgun.org";
int port = 25;
String login = "login";
String password = "password";
String from = "from#example.com";
AuthenticatingSMTPClient client = null;
try {
client = new AuthenticatingSMTPClient();
// optionally set a timeout to have a faster feedback on errors
client.setDefaultTimeout(10 * 1000);
// you connect to the SMTP server
client.connect(hostname, port);
// you say helo and you specify the host you are connecting from, could be anything
client.ehlo("localhost");
// if your host accepts STARTTLS, we're good everything will be encrypted, otherwise we're done here
if (client.execTLS()) {
client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, login, password);
checkReply(client);
client.setSender(from);
checkReply(client);
String address = "";
if (toAddress != null) {
for (String to : toAddress) {
if(to != null && to.length() > 0) {
client.addRecipient(to);
if (address.length() == 0) {
address += ",";
}
address += to;
}
}
}
if(address.length() == 0){
logger.warning("No address specified for mail message");
return null;
}
checkReply(client);
Writer writer = client.sendMessageData();
if (writer != null) {
SimpleSMTPHeader header = new SimpleSMTPHeader(from, address, subject);
writer.write(header.toString());
writer.write(body);
writer.close();
if (!client.completePendingCommand()) {// failure
throw new IOException("Failure to send the email " + client.getReply() + client.getReplyString());
}
} else {
throw new IOException("Failure to send the email " + client.getReply() + client.getReplyString());
}
} else {
throw new IOException("STARTTLS was not accepted " + client.getReply() + client.getReplyString());
}
} catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException e) {
logger.severe("Error sending email",e);
} finally {
if (client != null) {
try {
client.logout();
client.disconnect();
} catch (Exception e) {
logger.warning("Error closing email client: " + e.getMessage());
}
}
}
return null;
}
};
task.execute();
}
private static void checkReply(SMTPClient sc) throws IOException {
if (SMTPReply.isNegativeTransient(sc.getReplyCode())) {
throw new IOException("Transient SMTP error " + sc.getReplyString());
} else if (SMTPReply.isNegativePermanent(sc.getReplyCode())) {
throw new IOException("Permanent SMTP error " + sc.getReplyString());
}
}

Android How to Configure XMPP Conference - Chat room

I am developing one chat application , But it not work properly, giving different-differet error like 406 or 407 , So please advice me My following code for that is proper or not ,
First Login When Application Start :
public void LoginWithUser() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
SASLAuthentication.unregisterSASLMechanism("org.jivesoftware.smack.sasl.javax.SASLDigestMD5Mechanism");
SmackInitialization initialization = new SmackInitialization();
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(Constants.SERVICE);
config.setHost(Constants.HOST);
config.setPort(Constants.PORT);
config.setResource("myresource");
config.setDebuggerEnabled(true);
config.setKeystoreType("AndroidCAStore");
config.setConnectTimeout(100000);
try {
config.setUsernameAndPassword(getUserName(), password);
} catch (Exception e) {
e.getMessage();
}
Constants.connection = new XMPPTCPConnection(config.build()); //new XMPPConnection(Constants.connConfig);
try {
if (!Constants.connection.isConnected()) {
Constants.connection.connect();
}
Log.i("ChatActivity", "Connected to "
+ Constants.connection.getHost());
} catch (XMPPException ex) {
Log.e("ChatActivity",
"Failed to connect to " + Constants.connection.getHost());
Log.e("ChatActivity", ex.toString());
// setConnection(null);
} catch (IOException | SmackException e) {
e.printStackTrace();
Log.e("my error outer", e.getMessage() + " <- Understand 0 ? !!!");
}
try {
Log.d("chat : user name", getUserName());
try {
Log.d("chat : password", AESCrypt.decrypt(Constants.key_store_pair, enc_login_key));
} catch (Exception e) {
e.printStackTrace();
}
try {
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
Constants.connection.login(getUserName(), password);
Constants.connection.getServiceName();
Log.d("service name=", Constants.connection.getServiceName());
} catch (Exception e) {
e.printStackTrace();
Log.e("my error inner", e.getMessage() + " <- Understand 1 ? !!!");
}
Log.i("ChatActivity", "Logged in as "
+ Constants.connection.getUser());
Log.i("You are valid user",
"your Token is " + Constants.connection.getUser());
} catch (Exception ex) {
}
}
});
t.start();
}
It connected Successfully...
After when I creating New Conference Room at that time i register that conference room by calling following method :
private MultiUserChat createGroupChat(XMPPConnection connection,String room_id, String groupName, String registered_beam_iddd) throws XMPPException, SmackException {
// This code call when creating new conference room
Constants.mucM = MultiUserChatManager.getInstanceFor(connection); //new MultiUserChatManager(connection, registered_beam_iddd + "#" + groupName);
Constants.muc = Constants.mucM.getMultiUserChat(registered_beam_iddd + "#" + groupName);
if(Constants.connection.isConnected())
{
if(Constants.connection.isAuthenticated()) {
Constants.muc.createOrJoin(room_id + "#" + groupName); //
Form form = Constants.muc.getConfigurationForm();
Form submitForm = form.createAnswerForm();
Constants.muc.sendConfigurationForm(submitForm);
Log.d("Room Created : Name : " , room_id + "#" + groupName);
}
else
{
//Toast.makeText(getActivity(),"Authenicated false",Toast.LENGTH_LONG).show();
Log.d("ooo", "authentication failed in AddBeam");
}
}
else
{
Toast.makeText(getActivity(),"Connection Loss",Toast.LENGTH_LONG).show();
}
return Constants.muc;
//onesecond
}
When I Click on number of conference room ( listview ) , that means when i enter on any of my conference room , i call following method to join room and get history,
private MultiUserChat joinGroupChat(XMPPConnection connection, String room_id, String groupName, String registered_beam_iddd) throws XMPPException, SmackException {
// This code called when user enter in Chat-conference room
if (Constants.connection.isConnected()) {
if (Constants.muc == null) {
Constants.mucM = MultiUserChatManager.getInstanceFor(connection); //new MultiUserChatManager(connection, registered_beam_iddd + "#" + groupName);
Constants.muc = Constants.mucM.getMultiUserChat(registered_beam_iddd + "#" + groupName);
}
if (Constants.connection.isAuthenticated()) {
if (!Constants.muc.isJoined()) {
DiscussionHistory history = new DiscussionHistory();
history.setMaxStanzas(20);
Constants.muc.join(room_id + "#" + groupName, "password", history, Constants.connection.getPacketReplyTimeout()); // #conference.tubsystems.com
} else {
Log.d("joined: ", room_id + "#" + groupName);
}
} else {
Log.d("ooo", "authentication failed in AddBeam");
}
} else {
Toast.makeText(getApplicationContext(), "Connection Loss", Toast.LENGTH_LONG).show();
try {
Constants.connection.connect();
Log.i("ChatActivity", "Connected to "
+ Constants.connection.getHost());
} catch (Exception ex) {
Log.e("ChatActivity",
"Failed to connect to " + Constants.connection.getHost());
Log.e("ChatActivity", ex.toString());
// setConnection(null);
}
}
return Constants.muc;
//onesecond
}
For Sending Message to conference :
private void sendmessage(String text, String room) {
String to = beamId + "#"+groupname;
Message msg = new Message(to, Message.Type.groupchat);
msg.setBody(text);
if (Constants.connection != null) {
try {
Constants.connection.sendPacket(msg);
Log.d("Send to room : Name : ", to);
} catch (Exception e) {
Log.d("ooo", "msg exception" + e.getMessage());
}
messages.add(text);
msg_send_receive_val = 1;
new setListAdapter().execute();
}
}
But it giving Some time connection error , some time 406 or 407 error and when i first time enter in the conference room at that time only it display past history message and then automatically removed, and message also not sending some times and some times sending , i dont know what is problem , while sending message it giving 406-407 modify- not acceptable error and some times giving other error.
I don't know but anything missing in above code , or anything other required to configure conference room ? Please help me as much fast as possible.
Thanks in advance.

Node Server with Android and Browser Client

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.

Categories

Resources