I am using Java Bluecove to establish a connection between my pc and a remote bluetooth device.
I use a a DiscoveryListener object to discover the URL of a certain service on the device; then I use that string URL as argument of Connector.open(URL) to open the connection but I get:
Connection timeout; [10060] A connection attempt failed because the
connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to
respond.
Here are two snippets from my program. The first one searches for a specified set of services
UUID[] uuidSet = new UUID[1];
uuidSet[0] = new UUID(0x1101); //serial port
int[] attrIDs = new int[]{0x0100};
LocalDevice localDevice = LocalDevice.getLocalDevice();
DiscoveryAgent agent = localDevice.getDiscoveryAgent();
agent.searchServices(attrIDs, uuidSet, device, transport); //if the specified service is found its URL is print to screen; so I know it
The following code is to establish the connection.
String bt_addr = remDev.getBluetoothAddress(); //remDev is the remote device; I am sure it's the correct one
try {
connection = (StreamConnection) Connector.open("btspp://" + bt_addr + ":1;authenticate=false;encrypt=false;master=true;"); //HERE OCCURS THE TIMEOUT !
} catch (javax.bluetooth.BluetoothConnectionException e) {}
Now, it may be that there are other services on the meter but I only look for 0x1101 which is not the one I have to use to connect to. But I don't know how to look for different services.
Related
I have a server running in a machine (lets call it MACHINE1). In this file, I have created the start_server = websockets.serve(recv, "serverIP", port). The server is correctly running.
On the other side, I have one android application running working as a client connected to the server (note that both devices are running in the same network)
try {
uri = new URI("ws://" + serverIP + ":port");
} catch (URISyntaxException e) {
e.printStackTrace();
}
mWebSocketClient = new WebSocketClient(uri) {
// my code
}
As I mentioned below, currently the solution is setting serverIP to the IP of MACHINE1 (192.168...), and therefore, if I change the machine to another IP the connection will fail. Is there any way to create a general solution? I tried using localhost but I did not manage to connect to MACHINE1
I have a new project where I should connect to an SSH server, with a proxy (which is on-premise).
The problem is, that if I don't use proxy, I get an error saying "UnknownHost".
But when I use proxy, it says "JSchException ProxySOCKS5: com.jcraft.jsch.JSchException: fail in SOCKS5 proxy".
I'm pretty new to sockets, proxies and all these kinds of things, so every advice is appreciated.
JSch jsch = new JSch();
jsch.setKnownHosts("known_hosts");
com.jcraft.jsch.Session session = null;
com.jcraft.jsch.ProxySOCKS5 proxy = new ProxySOCKS5("localhost", 20004);
proxy.setUserPasswd(userName, password);
URL url = new URL("http", "<remoteUrl>", 22, filePath, null);
session = jsch.getSession(userName, hostName, 22);
session.setPassword(password);
session.setProxy(proxy );
session.connect(10000);
I did try a different direction, where I don't use jsch, only java.net. That code:
SocketAddress addr = new InetSocketAddress("localhost", 20004);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
final String encodedSubaccount = new String(Base64.encodeBase64(subaccount.getBytes()));
final String encodedLocationId = new String(Base64.encodeBase64(locationId.getBytes()));
char[] pwdHelp = [];
Authenticator.setDefault(new Authenticator() {
#Override
protected java.net.PasswordAuthentication getPasswordAuthentication() {
return new java.net.PasswordAuthentication("1." + encodedSubaccount + "." + encodedLocationId , pwdHelp);
}
});
URL url = new URL("http", "<remoteUrl>", 22, filePath, null);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
With this approach, there is no error, but when I try to getResponseMessage() or code, then it returns only -1 or null.
Can somebody help me out?
Thanks in advance
I'm not a java developer so I can help you only the infrastructure part of the problem.
UnknownHost: you cannot connect directly that's why you have to use proxy. UnknownHost means java/your machine cannot resolve DNS name to IP address, maybe that DNS name is an inside/private one.
As I see In your java code You try to connect HTTP protocol instead of SSH protocol.
What is the exact task?
Somebody was provided You an on-premise SocksProxy IP and port, and you have to connect via to an inside SSH server?
OR
You have to connect with SSH protocol to the on-premise server to create a local SocksProxy, and you have to connect to an inside server via local SocksProxy?
In the 2. case you can test the connection with ssh command and a web browser:
SSH to on-premise: ssh -D 1080 on-premise_remote_hosntame_or_IP
Setup socksproxy in a webbrowser: Socks proxy ip: 127.0.0.1, port: 1080
In the web browser try to connect to an inside webserver
hi have at home a rasperry pi running a server java app, connected to de router with the dynamic DNS configured and the in/out communication ports openned.
When i run the android apication client througt 4g everithing is working sucessfull. But when i run the same app connected to the wifi on my local net, where the server are running, the server application looks like death.
Any ideas?
Thanks.
router config
I think the problem is related to your DNS. If you are connected using your wifi, you have to return a local IP-Address. Do you have any chance of configuring your router to return the raspberries local IP-Address for wifi-clients?
Take a look here: link
A simple solution, even if it is not very elegant, is adding the following conditions to your code:
If there is an error connecting to the Dyn DNS, try to connect to the local IP address. (In case you are in the Wifi LAN)
If the local IP address fails, try again your Dyn DNS (in case the user is a real user with real communication problems)
(repeat until the connection is successful)
You can also identify your testing devices (using Settings.Secure.ANDROID_ID, or the IMEI) and use the local IP only for them. Another option is making the URL configurable (with a hidden option for example).
Because of my app can run local, only needs to connect to server for updates. I have block the connection on the server app if the ip from client and server are equals.
At the moment is the best solution to keep the server app running properly.
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new
InputStreamReader(whatismyip.openStream()));
String ip = in.readLine();
try {
SSLServerSocketFactory sslFactory = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
SSLServerSocket ss = (SSLServerSocket) sslFactory.createServerSocket(PORT);
int idSession = 0;
while (true) {
SSLSocket socket = (SSLSocket)ss.accept();
if(socket.getInetAddress().getHostAddress().equals(ip)){
if (socket != null && !socket.isClosed()) {
socket.close();
}
}
((ServidorThread) new ServidorThread(socket, idSession)).start();
idSession++;
}
} catch (IOException ex) {
ex.printStackTrace(System.out);
Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
}
}
I'm trying to create a SignalR connection between an ASP.NET server (SignalR-Server 3.0.0) and an Android client on a real device. So far I've managed to successfully establish a connection on the same computer using a console application client targeting the IP http://127.0.0.1:5000/.
The server computer and the Android device are both connected to the same LAN (over Wi-Fi), so I tried to set the target IP to be the server computer LAN IP, but an exception is thrown:
java.net.SocketTimeoutException: failed to connect to /192.168.14.167
(port 5000) after 15000ms
Here's the relevant client app, using SignalR Java client:
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String serverUrl = "http://192.168.14.167:5000/signalr";
mHubConnection = new HubConnection(serverUrl);
mHubProxy = mHubConnection.createHubProxy("Hub");
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return;
}
Am I missing anything/doing anything wrong? Any help will be appreciated.
I'm having the following problem:
When I try to createTcpServer with my external IP address (the PC's IP and not my local IP = the one we see as an output after running ipconfig in cmd.exe) the following error occurs:
Error with Server: Exception opening port "9092" (port may be in use), cause: "java.net.BindException: Cannot assign requested address: JVM_Bind" [90061-169]
However, the port is not in use. I've checked that using netstat -a -n .
I have enabled my external IP and I have disabled the firewall from the router. My external IP can now be pinged.
Please help me.
Update: Here is my code to start the tcp server.
package businessApp;
import org.h2.tools.Server; //imports the server utility
public class startTcpServerForH2 {
Server server; //the server's instance variable
private static final String SERVER_IP = "192.168.1.101"; //fixed IP of the server
private static final String SERVER_PORT = "9092"; //fixed port the server is listening to
public void tcpServer() { //method responsible to create the tcp server
optionPane optPane = new optionPane(); //option pane for debugging purposes, shows the server's status
try { //catches any server related errors, if the connection is broken etc.
//server uses the IP and port defined earlier, allows other computers in the LAN to connect and implements the secure socket layer (SSL) feature
server = Server.createTcpServer( //create tcp server
new String[] { "-tcpPort" , SERVER_PORT , "-tcpAllowOthers" , "-tcpSSL" }).start();
System.out.println(server.getStatus()); //prints out the server's status
optPane.checkServerStatus(server.getStatus()); //prints out the server's status on the option pane as well
} catch(Exception ex){
System.out.println("Error with Server: " + ex.getMessage());
}
}
public static void main(String[] args){
startTcpServerForH2 tcpServ = new startTcpServerForH2(); //create a new server object
tcpServ.tcpServer(); //starts the tcp server
}
}
Second Update: here is the h2Connection code.
package businessApp;
import java.sql.*; //imports sql features
//Class responsible for connection with H2 Database Engine
public class h2Connection {
Connection conn; //connection variable
DatabaseMetaData dbmd; /** Metadata variable which include methods such as the following:
* 1) Database Product Name
* 2) Database Product Version
* 3) URL where the database files are located (in TCP mode)
*/
Statement stm; //statements variable
ResultSet rst; //result sets variable
private static final String SERVER_IP = "..."; //here I enter my WAN_IP
private static final String SERVER_PORT = "9092";
public Connection connectionToH2(Connection connt) {
optionPane optPane = new optionPane(); //create new option pane object
String outputConn = null; //declare & initialize string which will hold important messages
try {
Class.forName("org.h2.Driver"); //Driver's name
/** The String URL is pertained of the following:
* 1) jdbc which java implements so that it can take advantage of the SQL features
* 2) Which Database Engine will be used
* 3) URL where the files will be stored (as this is a TCP connection)
* 4) Schema: businessApp
* 5) Auto server is true means that other computers can connect with the same databse at any time
* 6) Port number of the server is also defined
*/
String url = "jdbc:h2:tcp://" + SERVER_IP + ":" + SERVER_PORT + "/C:/Databases/businessApp;IFEXISTS=TRUE";
System.out.println(url); //prints out the url the database files are located as well as the h2 features used (SSL)
connt = DriverManager.getConnection(url, "sa", ""); //Driver Manager defines the username & password of the database
System.out.println(connt.getCatalog()); //prints out the database schema
optPane.checkServerStatus(connt.getCatalog()); //prints out the database schema on the option pane as well
connt.setAutoCommit(false); //set AutoCommit to false to control commit actions manually
//outputs H2 version and the URL of the database files which H2 is reading from, for confirmation
dbmd = connt.getMetaData(); //get MetaData to confirm connection
outputConn = "Connection to "+dbmd.getDatabaseProductName()+" "+
dbmd.getDatabaseProductVersion()+ " with the URL " + dbmd.getURL()+" was successful.\n";
System.out.println(outputConn); //outputs the message on the system (NetBeans compiler)
optPane.checkH2Connection(outputConn); //outputs the message on top of the frame
} catch (ClassNotFoundException ex){ //In case there is an error for creating the class for the Driver to be used
System.out.println("Error creating class: " + ex.getMessage());
} catch(SQLException ex){ //Any error associated with the Database Engine
System.out.println("SQL error: " + ex.getMessage());
optPane.checkServerStatus("SQL error: " + ex.getMessage());
}
return connt; //As the method is not void, a connection variable must be returned
}
}
When I want to connect to the h2 database, I make a new h2Connection object and use it to connect. I have followed the H2 manual word by word. What more do you need?
As suggested in the command line help shown below, Protection against Remote Access advises the following:
By default this database does not allow connections from other machines when starting the H2 Console, the TCP server, or the PG server. Remote access can be enabled using the command line options -webAllowOthers, -tcpAllowOthers, -pgAllowOthers.
See the documentation for important caveats regarding these options.
Addendum: Works for me, as long as I restart the Server after opening the firewall; you don't need the setProperty() line at all; the LAN IP to which your WAN_IP forwards port 9092 should be your host IP address; then you can open a shell via your WAN_IP:
java -cp h2.jar org.h2.tools.Shell -url
jdbc:h2:tcp://WAN_IP/~/path/to/test;ifexists=true"
Command line help:
$ java -cp .:/opt/h2/bin/h2.jar org.h2.tools.Shell -?
Interactive command line tool to access a database using JDBC.
Usage: java org.h2.tools.Shell
Options are case sensitive. Supported options are:
[-help] or [-?] Print the list of options
[-url ""] The database URL (jdbc:h2:...)
[-user ] The user name
[-password ] The password
[-driver ] The JDBC driver class to use (not required in most cases)
[-sql ""] Execute the SQL statements and exit
[-properties ""] Load the server properties from this directory
If special characters don't work as expected, you may need to use
-Dfile.encoding=UTF-8 (Mac OS X) or CP850 (Windows).
See also http://h2database.com/javadoc/org/h2/tools/Shell.html
$ java -cp /opt/h2/bin/h2.jar org.h2.tools.Server -?
Starts the H2 Console (web-) server, TCP, and PG server.
Usage: java org.h2.tools.Server
When running without options, -tcp, -web, -browser and -pg are started.
Options are case sensitive. Supported options are:
[-help] or [-?] Print the list of options
[-web] Start the web server with the H2 Console
[-webAllowOthers] Allow other computers to connect - see below
[-webDaemon] Use a daemon thread
[-webPort ] The port (default: 8082)
[-webSSL] Use encrypted (HTTPS) connections
[-browser] Start a browser connecting to the web server
[-tcp] Start the TCP server
[-tcpAllowOthers] Allow other computers to connect - see below
[-tcpDaemon] Use a daemon thread
[-tcpPort ] The port (default: 9092)
[-tcpSSL] Use encrypted (SSL) connections
[-tcpPassword ] The password for shutting down a TCP server
[-tcpShutdown ""] Stop the TCP server; example: tcp://localhost
[-tcpShutdownForce] Do not wait until all connections are closed
[-pg] Start the PG server
[-pgAllowOthers] Allow other computers to connect - see below
[-pgDaemon] Use a daemon thread
[-pgPort ] The port (default: 5435)
[-properties ""] Server properties (default: ~, disable: null)
[-baseDir ] The base directory for H2 databases (all servers)
[-ifExists] Only existing databases may be opened (all servers)
[-trace] Print additional trace information (all servers)
The options -xAllowOthers are potentially risky.
For details, see Advanced Topics / Protection against Remote Access.
See also http://h2database.com/javadoc/org/h2/tools/Server.html