I am new to signalR, tried to connect to a hub and got a connectionId after successful connection.
my code
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String host = "url";
HubConnection connection = new HubConnection(host);
HubProxy hub = connection.createHubProxy("pttdashboardhub");
ClientTransport clientTransport = new ServerSentEventsTransport(connection.getLogger());
SignalRFuture<Void> signalRFuture = connection.start(clientTransport);
try {
signalRFuture.get();
System.out.println(connection.getConnectionId());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
hub.on("onEvent",
new SubscriptionHandler1<String>() {
#Override
public void run(String s) {
System.out.println("================ "+s);
}
}, String.class);
server code
var eventHub = GlobalHost.ConnectionManager.GetHubContext<EventHub>();
var result = eventHub.Clients.Group("pttdashboard").onEvent(data);
the problem comes when hub.on function executes i get nothing from the server.
Any help is appreciated.
You can use subscribe function instead of on function.
hub.subscribe("onEvent").addReceivedHandler(new Action<JsonElement[]>(){
#Override
public void run(JsonElement obj) {
System.out.println("================ "+s);
}
});
I hope this helps you.
Related
I am using Apache Mina SSHD to communicate with two Android devices. I have server-side code and client-side I'd like to establish a connection and start streaming data (byte array packet) from server to client and client to server until a button pressed to disconnect. How can I do this?
SERVER
I use this link SSHD SERVER stackOverflow
public void startSSHServer() {
int port = 22;
SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(port);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(
"src/test/resources/hostkey.ser"));
sshd.setSubsystemFactories(Arrays
.<NamedFactory<Command>>asList(new SftpSubsystem.Factory()));
sshd.setCommandFactory(new ScpCommandFactory());
sshd.setShellFactory(new ProcessShellFactory(new String[]{"/system/bin/sh", "-i", "-l"})); // necessary if you want to type commands over ssh
sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
#Override
public boolean authenticate(String u, String p, ServerSession s) {
return ("sftptest".equals(u) && "sftptest".equals(p));
}
});
try {
sshd.start();
} catch (IOException e) {
e.printStackTrace();
}
}
CLIENT
I use this link SSHD CLIENT geeksforgeeks
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
// Connection establishment and authentication
try (ClientSession session = client.connect(username, host, port).verify(10000).getSession()) {
session.addPasswordIdentity(password);
session.auth().verify(50000);
System.out.println("Connection establihed");
// Create a channel to communicate
channel = session.createChannel(Channel.CHANNEL_SHELL);
System.out.println("Starting shell");
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
channel.setOut(responseStream);
// Open channel
channel.open().verify(5, TimeUnit.SECONDS);
try (OutputStream pipedIn = channel.getInvertedIn()) {
pipedIn.write(command.getBytes());
pipedIn.flush();
}
// Close channel
channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED),
TimeUnit.SECONDS.toMillis(5));
// Output after converting to string type
String responseString = new String(responseStream.toByteArray());
System.out.println(responseString);
shellOutput.setText(responseString);
} catch (IOException e) {
e.printStackTrace();
} finally {
client.stop();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
Apologize for the long question!
I am new in SignalR. Please help me to solve my problem.
I have SignalR server in web, I am getting data from .net client site but unable to get data from my Android client side. When my debugger arrived to "hub.invoke" is just stop.
I have tired a lot with different codes but un-success.
If I unable to do above then I want to do that in my local server at my home. I have two laptops, one is running Win7 another Win8. I want to keep a signalR server in one of them and access from another. How can I do that? what kind of SignalR server API I will write? If you guys please help me step my step?
bellow is my tied code
String android_id = Settings.Secure.getString(arg0.getContext().getContentResolver(), Settings.Secure.ANDROID_ID);
HubConnection con = new HubConnection(Uri.parse("http://10.198.40.32:8090/login/").toString());
HubProxy hub = con.createHubProxy("NotificationHub");
con.start();
try {
hub.invoke( "userID", "password", android_id).get();
} catch (InterruptedException e) {
// Handle ...
System.out.print(e);
} catch (ExecutionException e) {
// Handle ...
System.out.print(e);
}
You can refer to my working sample code as the following. Then, you can replace Object.class by your own custom class:
public <T> void startSignalR(String transport, String serverUrl, final String userName, final Class<T> tClass) {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
Credentials credentials = new Credentials() {
#Override
public void prepareRequest(Request request) {
request.addHeader(HEADER_KEY_USERNAME, userName);
}
};
mConnection = new HubConnection(serverUrl);
mConnection.setCredentials(credentials);
mHub = mConnection.createHubProxy(SERVER_HUB_CHAT);
if (transport.equals("ServerSentEvents")) {
mTransport = new ServerSentEventsTransport(mConnection.getLogger());
} else if (transport.equals("LongPolling")) {
mTransport = new LongPollingTransport(mConnection.getLogger());
}
mAwaitConnection = mConnection.start(mTransport);
try {
mAwaitConnection.get();
} catch (InterruptedException e) {
e.printStackTrace();
return;
} catch (ExecutionException e) {
e.printStackTrace();
return;
}
mHub.on("broadcastMessage",
new SubscriptionHandler1<Object>() {
#Override
public void run(final Object msg) {
final String finalMsg;
Gson gson = new Gson();
Object object = gson.fromJson(msg.toString(), tClass);
Field[] fields = object.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
try {
System.out.println("Value = " + fields[i].get(object));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
, Object.class);
...
}
A full source code of SignalR for Android/Java, you can find here at GitHub
Hope this helps!
I recently started learning android development (am new to java as well) and I am currently working on a chat/messenger application
The problem I am facing, as the title says, is that the listview in which the messages are shown does not update on the device, unless scrolled, but it works fine on the virtual machine. I only tested on LG Optimus l5 II so far, but i need to fix this anyway.
I think it has something to do with multithreading, because this didn't happen until i added some new threads, so the adapter for listview, android manifest and rest I say are set up correctly. I can add them if it helps.
The 2 threads i added that might cause this:
Checks the connection status and if disconnected tries to reconnect.
The thread used for communicating with the server.
I tested running only with the second thread on, and the problem still occurs.
I want to specify this is the first time I try something like this (servers-client, multithreading, java, android (I'm still in college and they don`t teach us these kinds of stuff there) ), and had no documentation ahead regarding how I should set up the communication between the server and the client. This is the most efficient way I could think of.
this is at the end of onCreate:
StartConnectingRoutine(); // so you know where it all starts
and the code for it:
private void StartConnectingRoutine()
{
Thread t = new Thread()
{
#Override
public void run()
{
while(true)
{
if(!connected)
{
if( connect != null)
{
if(!connect.isAlive())
{
ConnectListener();
}
}
else
{
ConnectListener();
}
}
try {
sleep(CONNECTION_CHECK_TIME_MS); // this is set to 10000 (10 seconds)
} catch (InterruptedException e) {
Log.e("Intrerrupted", e.toString());
}
}
}
};
t.start();
}
and the connectListener():
private void ConnectListener()
{
Log.d("Connecting", "Connecting...");
connect = new Thread()
{
JSONObject info = new JSONObject();
String receivedMessage;
#Override
public void run()
{
try {
info.put("Name", user.GetName());
info.put("PORT", MY_PORT);
info.put("IPv4", getIpAddress());
} catch (JSONException e1) {
Log.e("JSON", "JSON error: " + e1.toString());
}
try
{
ServerSocket = new Socket(SERVER_IP, SERVER_PORT);
dis = new DataInputStream(ServerSocket.getInputStream());
dos = new DataOutputStream(ServerSocket.getOutputStream());
dos.writeUTF(info.toString());
dos.flush();
String response = dis.readUTF();
if(response.equals("connected"))
{
Log.d("Connect", "Connected!");
connected = true;
}
else
Log.d("Connect", "Failed to connect!");
while(connected)
{
receivedMessage = dis.readUTF();
DisplayNewMessage(new MMessage(receivedMessage, MMessage.MessageType.Received));
}
}catch(SocketException e)
{
try {
if(connected)
{
ServerSocket.close();
dis.close();
dos.close();
connected = false;
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
catch(Exception e)
{
Log.d("Connect", "Failed to connect");
Log.e("Connect", e.toString());
connected = false;
}
}
};
connect.start();
}
Fixed:
Reconnecting thread (i tried using asyncTask for this too, but it wouldn`t open the other asyncTask, even if I tried to open it from onProgressUpdate()-which it is supposed to be able to run ui thread components):
private void startConnectingRoutine()
{
Thread t = new Thread()
{
#Override
public void run()
{
Log.d("ConnectingRoutine", "Started connecting routine.");
while(true)
{
if(!connected)
{
startListener();
}
try {
sleep(CONNECTION_CHECK_TIME_MS);
} catch (InterruptedException e) {
Log.e("Intrerrupted", e.toString());
}
}
}
};
t.start();
}
Listener thread:
private void startListener()
{
new Listener().execute();
}
.
private class Listener extends AsyncTask<Long, String, Long>
{
#Override
protected Long doInBackground(Long... params) {
Log.d("Connecting...", "Connecting...");
JSONObject info = new JSONObject();
String receivedMessage;
try {
info.put("Name", user.GetName());
info.put("PORT", MY_PORT);
info.put("IPv4", getIpAddress());
} catch (JSONException e1) {
Log.e("JSON", "JSON error: " + e1.toString());
}
try
{
serverSocket = new Socket(SERVER_IP, SERVER_PORT);
dis = new DataInputStream(serverSocket.getInputStream());
dos = new DataOutputStream(serverSocket.getOutputStream());
dos.writeUTF(info.toString());
dos.flush();
String response = dis.readUTF();
if(response.equals("connected"))
{
Log.d("Connect", "Connected!");
connected = true;
}
else
Log.d("Connect", "Failed to connect!");
while(connected)
{
receivedMessage = dis.readUTF();
publishProgress(receivedMessage);
}
}
catch(Exception e)
{
Log.d("Connect", "Failed to connect");
Log.e("Connect", e.toString());
return null;
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
displayNewMessage(new MMessage(values[0], MMessage.MessageType.Received));
}
#Override
protected void onPostExecute(Long result) {
super.onPostExecute(result);
connected = false;
try{
if(serverSocket != null)
serverSocket.close();
if(dis != null)
dis.close();
if(dos != null)
dos.close();
}catch(Exception e)
{
Log.e("Listener", "There was a problem closing the connection: " + e.toString());
}
}
}
There are perhaps multiple things going wrong here, but two that jump out are:
You're calling DisplayNewMessage() from outside the UI thread.
You're not notifying the adapter that its dataset has changed.
I urge you to look in to better mechanisms for executing tasks in the background than simply creating a Thread. Using AsyncTasks would be a good start, but you'll need to take special care to handle tasks between configuration changes (such as rotating the device).
Furthermore, your code is very difficult to read as you capitalize your method names. This is against Java code conventions. You will make things easier for yourself by formatting your code neatly (a good IDE helps with that) and learning to follow conventions!
I have created a client and a server, which both work fine and have no trouble connecting. Now I would like to be able to connect from my android phone to the server. I have imported the kryonet library and copy-pasted the client code into a new android project. The code gave me some errors, but I fixed those. When I tried testing my app, it didn't give me any errors, but my server wasn't getting any connections either. I looked a bit in the LogCat logs, and found out it keeps sticking at "Connecting..". I am totally stuck. This is my android code:
public void openSocket(View view){
Log.i(TAG, "test1");
EditText portText= (EditText)findViewById(R.id.port);
String parts[] = portText.getText().toString().split(":");
partIP = parts[0];
String partPort = parts[1];
port = Integer.parseInt(partPort);
try {
client = new Client();
client.start();
register();
pHandler = new PacketHandler();
connect();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void register() {
client.getKryo().register(Packet.class);
client.getKryo().register(Packet1Connected.class);
client.getKryo().register(String.class);
client.getKryo().register(String[].class);
client.getKryo().register(Object[].class);
}
public static void connect() {
try {
String IP = "*MY IP*:25565";
String[] Ip = IP.split(":");
String ipFinal = Ip[0];
int port = Integer.parseInt(Ip[1]);
client.connect(5000, ipFinal, port, port);
} catch (IOException e) {
try {
Thread.sleep(15000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
System.out.println("Trying to connect.");
connect();
}
Packet1Connected packet = new Packet1Connected();
packet.id = "Android";
client.sendTCP(packet);
}
And this is my normal client code:
public static void main(String[] args) {
try {
client = new Client();
client.start();
register();
pHandler = new PacketHandler();
new Main();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void register() {
client.getKryo().register(Packet.class);
client.getKryo().register(Packet1Connected.class);
client.getKryo().register(String.class);
client.getKryo().register(String[].class);
client.getKryo().register(Object[].class);
}
public Main() {
try {
connect();
Thread t = new Thread(this);
t.start();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void connect() {
try {
String IP = "*MY IP*:25565";
String[] Ip = IP.split(":");
String ipFinal = Ip[0];
int port = Integer.parseInt(Ip[1]);
client.connect(5000, ipFinal, port, port);
} catch (IOException e) {
try {
Thread.sleep(15000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
System.out.println("Trying to connect.");
connect();
}
Packet1Connected packet = new Packet1Connected();
packet.id = System.getProperty("user.name");
client.sendTCP(packet);
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(3000);
if (!client.isConnected())
connect();
} catch (InterruptedException e) {
pHandler.checkException(e);
}
}
}
}
So this:
client.connect(5000, ipFinal, port, port);
is the line it gets stuck on, on android. The normal client just connects normally.
Now my question is, is there something wrong with my android code, or is it just the device, or wifi connection?
If it helps, I tried testing it on my samsung galaxy nexus, which is rooted.
Thanks in advance.
Hey how can i display every response from the xmpp server?
I try to send messages but a lot of them get lost on the way so i want to check the response of the server. I am using smack 3.3.1 sending to the facebook xmpp port.
DeliveryReceiptManager and/or MessageEventManager wont show anything so i would like to see everything the server is responding!
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com",5222);
config.setSASLAuthenticationEnabled(true);
XMPPConnection connection = new XMPPConnection(config);
try {
//ESTA LINEA HACE QUE NO DE TIMEOUT
SmackConfiguration.setPacketReplyTimeout(15000);
XMPPConnection.DEBUG_ENABLED = true;
SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM", SASLXFacebookPlatformMechanism.class);
SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
connection.connect();
String apiKey = "1234567";
String accessToken = "";
connection.login(apiKey, accessToken);
}catch (XMPPException e){
e.printStackTrace();
}
try {
DeliveryReceiptManager deliveryReceiptManager = DeliveryReceiptManager.getInstanceFor(connection);
deliveryReceiptManager.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(String s, String s2, String s3) {
System.out.println("REVEIVED RESPONCE");
System.out.println(s);
System.out.println(s2);
System.out.println(s3);
}
});
Chat chat = connection.getChatManager().createChat("1234567890#chat.facebook.com", new MessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
if(message.getType() == Message.Type.chat)
System.out.println(chat.getParticipant() + " says: " + message.getBody());
}
});
Message msg = new Message();
msg.setSubject("Invite");
msg.setBody("blablabla");
DeliveryReceiptManager.addDeliveryReceiptRequest(msg);
//MessageEventManager.addNotificationsRequests(msg, true, true, true, true);
chat.sendMessage(msg);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}catch (XMPPException e){
e.printStackTrace();
}
try {
Thread.sleep(10000);
}catch (InterruptedException e) {
e.printStackTrace();
}
Connection.DEBUG_ENABLED = true;