I have downloaded the official example of SignalR and it works fine when I try to connect from WinFormsClient to WinFormsServer. Everything just fine...
I downloaded the SignalR for android and tried to make a connection using the code below, but no success what so ever...I only get SocketTimeoutException. Here is my code, maybe someone can help me out!
I am trying this on a real device. Both PC and device are on same wifi network.
#Override
public void onClick(View v) {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String host = "http://192.168.0.11:8080/signalr";
HubConnection connection = new HubConnection(host);
HubProxy proxy = connection.createHubProxy("MyHub");
SignalRFuture<Void> awaitConnection = connection.start();
try {
awaitConnection.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
proxy.invoke("Send", new String[]{"Hahahahahhahaha", "shit shit shit!"});
proxy.on("AddMessage", new SubscriptionHandler2<String, String>() {
#Override
public void run(String p1, String p2) {
Log.d("result := ", p1 + " ---- " + p2);
}
}, String.class, String.class); }
});
Your firewall may block the connection.
Related
I have a problem with while getting offline messages from ejabberd server 18.01 via smack library.
I have a connector method
private static AbstractXMPPConnection connectToServer(String serverHost, Integer port, String userName, String userPassword) {
DomainBareJid xmppDomain = null;
try {
xmppDomain = JidCreate.domainBareFrom(serverHost);
} catch (XmppStringprepException e) {
System.out.println("XMPP Domain initialization exception " + e.getMessage());
return null;
}
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setXmppDomain(xmppDomain)
.setHost(serverHost)
.setPort(port)
.setDebuggerEnabled(true)
.setSendPresence(false)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
try {
connection.connect().login(userName, userPassword);
return connection;
} catch (XMPPException | SmackException | IOException | InterruptedException e) {
System.out.println("Something went wrong while connection to server: " + e.getMessage());
connection.disconnect();
return null;
}
}
and offline messages receiver
private XMPPConnection connection;
#Override
public void run() {
connection = Connector.getInstance();
if (connection != null) {
System.out.println("Start listening messages in the background");
String offlineMessageOffline = "Offline message is %s from %s";
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);
try {
if (offlineMessageManager.supportsFlexibleRetrieval()) {
offlineMessageManager.getMessages()
.forEach(message -> {
System.out.println(String.format(offlineMessageOffline, message.getBody(), message.getFrom()));
});
// offlineMessageManager.deleteMessages();
}
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException |
SmackException.NotConnectedException | InterruptedException e) {
System.out.println(String.format("Error while getting offline messages from server: by the reason %s", e.getMessage()));
}
try {
connection.sendStanza(new Presence(Presence.Type.available));
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
ChatManager chatManager = ChatManager.getInstanceFor(connection);
IncomingChatMessageListener listener = (entityBareJid, message, chat) -> {
System.out.println(String.format("Incoming message is %s from %s", message.getBody(), message.getFrom()));
};
chatManager.addIncomingListener(listener);
} else {
System.out.println("Connection has not been established. Please try to choose option 1");
}
}
I start running message listener at the background. I see that database has an offline message and in the dubug node I see that offlineMessageManager.getMessageCount() returns the proper number of offline messages but method offlineMessageManager.getMessages() returns noting. The smack version is 4.2.3 but earlier version has the same problem
UPDATED
I found a workaround because it doesn't look like a obvious solution
public class ListenMessagesFromServerCommand implements Runnable {
private XMPPConnection connection;
#Override
public void run() {
connection = Connector.getInstance();
if (connection != null) {
System.out.println("Start listening messages in the background");
String offlineMessageOffline = "Offline message is %s from %s";
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);
try {
if (offlineMessageManager.supportsFlexibleRetrieval() && offlineMessageManager.getMessageCount() > 0) {
List<String> messagesNodes = offlineMessageManager.getHeaders().stream()
.map(OfflineMessageHeader::getStamp)
.collect(Collectors.toList());
offlineMessageManager.getMessages(messagesNodes)
.forEach(message -> {
System.out.println(String.format(offlineMessageOffline, message.getBody(), message.getFrom()));
});
offlineMessageManager.deleteMessages();
}
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException |
SmackException.NotConnectedException | InterruptedException e) {
System.out.println(String.format("Error while getting offline messages from server: by the reason %s", e.getMessage()));
}
try {
connection.sendStanza(new Presence(Presence.Type.available));
} catch (SmackException.NotConnectedException | InterruptedException e) {
System.out.println("Error sending presence available type " + e.getMessage());
}
ChatManager chatManager = ChatManager.getInstanceFor(connection);
IncomingChatMessageListener listener = (entityBareJid, message, chat) -> {
System.out.println(String.format("Incoming message is %s from %s", message.getBody(), message.getFrom()));
};
chatManager.addIncomingListener(listener);
} else {
System.out.println("Connection has not been established. Please try to choose option 1");
}
}
}
Does anyone know how I can send custom commands using the ObdRawCommand in pires Java api? I have little to no experience with this api and I have contacted the creator but I haven't gotten any answer yet.
I have searched online for some project that uses the ObdRawCommand to send custom commands but I can't find anything.
So any help is appreciated!
Snippet
public void run() {
OBDcmds();
try {
ModuleVoltageCommand voltageCommand = new ModuleVoltageCommand();
OdbRawCommand command1 = new OdbRawCommand("22 40 28");
while (!Thread.currentThread().isInterrupted()) {
guiHandler(Constants.VOLTAGE_STATUS, 0, voltageCommand.getFormattedResult());
guiHandler(Constants.cmd1_STATUS, 0, command1.getFormattedResult());
Log.d("Log", "Voltage:" + voltageCommand.getFormattedResult());
Log.d("Log", "cmd1:" + command1.getFormattedResult()); //null
try {
voltageCommand.run(mmInStream, mmOutStream);
command1.run(mmInStream, mmOutStream);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("inside catch before while");
}
}
private void OBDcmds() { // execute commands
try {
new EchoOffCommand().run(mmInStream, mmOutStream);
new LineFeedOffCommand().run(mmInStream, mmOutStream);
new TimeoutCommand(125).run(mmInStream, mmOutStream);
new SelectProtocolCommand(ObdProtocols.AUTO).run(mmInStream, mmOutStream); //ISO_15765_4_CAN
new ModuleVoltageCommand().run(mmInStream, mmOutStream);
} catch (Exception e) {
Log.v("OBDcmds", "e");
// handle errors
}
}
I was right about how to send custom commands.
OdbRawCommand command1 = new OdbRawCommand("custom cmd here");
I have a problem using JXSE.
Let's say i have a rendezVous peer and an Edge peer, not on the same local network.
The rendezVous peer create a peerGroup "test", and publish an advertisement in this group with the name "test advertisement"
Let's say i'm sure than my EdgePeer is connected to the rendezVous peer. I can find the existing group "test" with netpeerGroup.getRemoteAdvertisements().
But i don't know how to join this existing group. I tried netpeergroup.newGroup(testAdv), with testAdv = the founded peerGroupAdvertisement.
I can't find the Advertisement "test advertisement" in the "test" PeerGroup.
But if i do all thats things locally, it works. Maybe i don't understand the difference on how jxta works locally and over internet.
here the code for creating or joining a group :
public void addGroup(final String name) {
ModuleImplAdvertisement mAdv = null;
PeerGroup group = null;
temp = null;
defaultGroup.getDiscoveryService().getRemoteAdvertisements(null, DiscoveryService.GROUP,
"Name", name, 1, new DiscoveryListener() {
#Override
public void discoveryEvent(DiscoveryEvent event) {
Enumeration<Advertisement> advs = event.getResponse().getAdvertisements();
while(advs.hasMoreElements()) {
System.out.println("groupe found");
PeerGroupAdvertisement adv = (PeerGroupAdvertisement) advs.nextElement();
System.out.println("group name : " + adv.getName());
try {
temp = defaultGroup.newGroup(adv);
System.out.println("group joined");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
try {
Thread.sleep(10000);
System.out.println("waiting for group ...");
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(temp == null) {
try {
System.out.println("creating new group ..");
mAdv = defaultGroup.getAllPurposePeerGroupImplAdvertisement(); /* Getting the advertisement of implemented modules */
temp = defaultGroup.newGroup(generatePeerGroupID(name), mAdv, name, name); /* creating & publishing the group */
getDefaultGroup().getDiscoveryService().remotePublish(temp.getPeerGroupAdvertisement());
} catch (Exception e) {
e.printStackTrace();
}
}
finally found the problem. You had to start the RendezVous service on each groups, and not only the netPeerGroup.
That's why my software works locally but not on internet.
My server closes after one clients disconnects,and I can write only one more message then it crashes.I wonder why,since I only close the client socket when it types "EXIT SERVER" .This is the exception it throws:
java.io.EOFException
This is my code :
import java.net.*;
import java.io.*;
public class ServerPeer extends Thread {
Socket _socket;
String username;
public ServerPeer(Socket _socket) {
this._socket = _socket;
}
public void sendMessage(String _username, String _message) throws IOException {
ObjectOutputStream _obj = new ObjectOutputStream(
_socket.getOutputStream());
_obj.writeObject(new Message(_username, _message));
_obj.flush();
}
public synchronized void run() {
try {
ObjectInputStream _ois = new ObjectInputStream(_socket.getInputStream());
Message _message;
while (_socket.isConnected()) {
_message = (Message) _ois.readObject();
String divide = _message.getAll().substring(0, _message.getAll().indexOf(":"));
username = divide;
Server.listofusers.add(username);
for (ServerPeer sp : Server.listofpeers) {
if (_message.getAll().contains("EXIT SERVER")) {
Server.listofpeers.remove(sp);
_socket.close();
}
if (_message instanceof PrivateMessage) {
PrivateMessage privm = (PrivateMessage) _message;
for (ServerPeer sp2 : Server.listofpeers) {
if (sp2.username.equals(privm.getReceiver())) {
sp2.sendMessage(divide, privm.getAll());
String priv = privm.getAll().replaceAll("/w", "");
System.out.println(priv);
break;
}
}
} else {
sp.sendMessage(divide, _message.getAll());
System.out.println(_message.getAll());
}
}
_ois = new ObjectInputStream(_socket.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Server Class:
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
static ServerConfig _svconfig = new ServerConfig();
public static ArrayList<ServerPeer> listofpeers = new ArrayList<ServerPeer>();
public static ArrayList<String> listofusers = new ArrayList<String>();
public static int i = 0;
// final static int _mysocket;
public static void main(String[] args) {
try {
final int _mysocket = _svconfig.getPORTNumber();
System.out.println("Wainting for clients.....");
ServerSocket _serversocket = new ServerSocket(_mysocket, _svconfig.getCLIENTSNumber());
while (listofpeers.size() <= _svconfig.getCLIENTSNumber()) {
Socket _clientsocket = _serversocket.accept();
ServerPeer _serverpeer = new ServerPeer(_clientsocket);
_serverpeer.start();
listofpeers.add(_serverpeer);
}
_serversocket.close();
} catch (MissingKeyException e) {
e.printStackTrace();
} catch (UnknownKeyException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (ConnectException e) {
e.printStackTrace();
} catch (BindException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (SocketException e) {
System.out.println("You have been disconnected");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
EDIT:
Exception thrown in the console of the client who disconnects:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2328)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2797)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:802)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at ClientPeer.serverEcho(ClientPeer.java:35)
at ClientPeer.run(ClientPeer.java:44)
BUILD STOPPED (total time: 1 minute 26 seconds)
From what I can tell i'd guess your code is incorrect, but it hard to tell without more code.
At first glance it seems that if too many people connect to your server you just shut down the entire server not just those connections.
while (listofpeers.size() <= _svconfig.getCLIENTSNumber()) {
Socket _clientsocket = _serversocket.accept();
ServerPeer _serverpeer = new ServerPeer(_clientsocket);
_serverpeer.start();
listofpeers.add(_serverpeer);
}
_serversocket.close();
A better approach would be something like the following. If too many users try to connect, just close the users connection.
ServerSocket _serversocket = new ServerSocket(_mysocket, _svconfig.getCLIENTSNumber());
boolean alive = true;
while (alive) {
try {
//Keep accepting connection request
Socket clientRequest = _serversocket.accept();
//Check if too many user are connected
if (listofpeers.size() <= _svconfig.getCLIENTSNumber()) {
ServerPeer _serverpeer = new ServerPeer(_clientsocket);
_serverpeer.start();
listofpeers.add(_serverpeer);
}else{
//Reject connection if too many connected
clientRequest.close();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
//When server dead close it down
_serversocket.close();
Hope this helps.
Your code must be exiting after the client thread is terminated, create a thread that has the server accept method that starts the client thread, something like this,
/**
*/
private class ServerListener extends Thread
{
/**
*/
public void run()
{
try
{
Socket clientSocket = socket.accept();
System.out.println("client connected => "+clientSocket.getInetAddress().getHostAddress());
ServerListener th = new ServerListener();
th.start();
ClientThread cth = new ClientThread(clientSocket);
cth.start();
clients.add(cth);
return;
}
catch (Exception e)
{
e.printStackTrace();
//Main.getInsatance().println(e);
//Main.getInstance().println("socket disconnected => "+clientSocket.getInetAddress().getHostAddress());
}
}
}
I have desktop and android applications, which connected by bluetooth(in desktop side I use Bluecove 2.1.1 library). Desktop application create bluetooth service then android application connects to it. I want to add logout functionality from both desktop and android sides. For example in desktop app user click disconnect, both desktop and android apps reset their connections and should be able to connect again. Here is bluetoothService code for desktop side:
public class BluetoothService
{
private static final String serviceName = "btspp://localhost:"
// + new UUID("0000110100001000800000805F9B34F7", false).toString()
// + new UUID("0000110100001000800000805F9B34F8", false).toString()
+ new UUID("0000110100001000800000805F9B34F9", false).toString()
+ ";name=serviceName";
private StreamConnectionNotifier m_service = null;
private ListenerThread m_listenerThread;
private DataOutputStream m_outStream;
public BluetoothService()
{
Open();
}
public void Open()
{
try
{
assert (m_service == null);
m_service = (StreamConnectionNotifier) Connector.open(serviceName);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void Start()
{
try
{
StreamConnection connection = (StreamConnection) m_service
.acceptAndOpen();
System.out.println("Connected");
m_listenerThread = new ListenerThread(connection);
Thread listener = new Thread(m_listenerThread);
listener.start();
m_outStream = new DataOutputStream(connection.openOutputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Send(String message)
{
assert (m_listenerThread != null);
try
{
m_outStream.writeUTF(message);
m_outStream.flush();
System.out.println("Sent: " + message);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Close()
{
try
{
m_service.close();
m_listenerThread.Stop();
m_listenerThread = null;
m_outStream.close();
m_outStream = null;
m_service = null;
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class ListenerThread implements Runnable
{
private DataInputStream m_inStream;
private boolean m_isRunning;
public ListenerThread(StreamConnection connection)
{
try
{
this.m_inStream = new DataInputStream(connection.openInputStream());
m_isRunning = true;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
;
}
public void run()
{
while (m_isRunning)
{
try
{
assert (m_inStream != null);
if (m_inStream.available() > 0)
{
String message = m_inStream.readUTF();
System.out.println("Received command: " + message);
CommandManager.getInstance().Parse(message);
}
}
catch (IOException e)
{
System.err.println(e.toString());
}
}
}
public void Stop()
{
m_isRunning = false;
try
{
m_inStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for restarting service I do:
BluetoothService::Close();
BluetoothService::Open();
BluetoothService::Start();
but seems I cannot reconnect. Maybe I should create service with different name?