How to connect to MySQL database from Android? - android

I try to connect to MySQL through mysql-connector-java-5.1.21-bin.jar library.
This is my code:
class Test {
private static final String CONNECTION = "jdbc:mysql://x.x.x.x:3306/db";
private void getMySQL() {
Connection con = null;
String str_res = "";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Properties for user and password.
Properties p = new Properties();
p.put("user","***");
p.put("password","***");
// Now try to connect
Connection c = DriverManager.getConnection(CONNECTION, p);
...
} catch (Exception e) {}
}
But I have a network exception:
com.mysql.jdbc.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago.
The driver has not received any packets from the server.
java.net.SocketException: The operation timed out
null
null
Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
0
0
What's wrong?

Related

MongoDB on Android - socket timeout

I want to connect my Android app to remote MongoDB database:
try {
String str = "";
MongoClientURI uri = new MongoClientURI("mongodb://byulent:mypass#ds231549.mlab.com:31549/mydb");
MongoClient mongoClient = new MongoClient(uri);
MongoDatabase db = mongoClient.getDatabase(uri.getDatabase());
MongoCollection<Document> photos = db.getCollection("photos");
FindIterable<Document> cursor = photos.find();
Iterator i = cursor.iterator();
while (i.hasNext()){
Log.d("obj", i.next().toString());
}
//Toast.makeText(context, "Succesfully connected to MongoDB", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e("mongodb", e.getMessage());
}
But when I try to get data from DB, I see this error:
E/mongodb: Timed out after 30000 ms while waiting to connect. Client view of cluster state
is {type=UNKNOWN, servers=[{address=ds231549.mlab.com:31549, type=UNKNOWN, state=CONNECTING,
exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by
{java.net.SocketTimeoutException: failed to connect to ds231549.mlab.com/34.245.70.193
(port 31549) after 20000ms}}]
Why this error occurs and how to fix it?

Async socket connection, Client GUI Hangs When Server is Disconnected TCP Communication

I am using Tcp Sockets For Communication Between CLR C++ (Server) to Android(Client) While using .Net For GUI.
While the data is communicated and received. Using a Background Worker in C++ Application
if(backgroundworker1->CancellationPending)
{
listenerSocket->Close(); // Listener Socket is Closed
netStream->Close();
serverSocket->Close();
serverSocket->Shutdown(SocketShutdown::Both);
e->Cancel;
break;
}
While in Android i am using Async Class for Execution and receiving text from socket to a Handler. While in Doinbackground Function i am using this code.
try
{
socket = new Socket(dstAddress, dstPort);
BufferedReader inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
do
{
try
{
if (!inputStream.ready())
{
if (message != null)
{
MainActivity.handler.obtainMessage(0, 0, -1,"Server: " + message).sendToTarget();
message = "";
}
}
int num = inputStream.read();
message += Character.toString((char) num);
Log.e(message,message);
}
catch (Exception classNot)
{
Log.e("Client TASK","classnot exception");
}
}
while (!message.equals("bye"));
inputStream.close();
socket.close();
}
I don't understand While am sending the Bye Message from the server and (Backgroundworker1->CancellationPending)
All server sockets are closed and Mobile Sockets are closed why is the UI Not Responding? Please Help..
The Problem was in Client in doinbackground Which calls the while loop again hence causing an exception because no data was received in the sockets and causing an exception. Finally added some sleep to the client that after some time the client query the server while if there is no message from the server the client shutdowns and shifted to postexecution function.

The socket stop t Socket.accept() in Android for TCP Server

I try to create a Simple TCP Server on Android phone and waiting for client.
I only want to implement the connection between TCPServer and Client , it doesn't need to transmit any data.
I have the another application for client , It use to connect to this TCPServer.
The code of TCPServerthread is like the following.
private class TCPServerThread implements Runnable
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
ServerSocket serverSocket = new ServerSocket(PORT);
//while loop
while (true) {
Log.i(TAG, "TCPServerThread...while loop");
try {
Socket socket = serverSocket.accept();
Log.i(TAG, "TCPServerThread...socket.getInetAddress() = " + socket.getInetAddress());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.i(TAG, "First IOException");
}
}
//while loop end
} catch (Exception e) {
// TODO: handle exception
//e.printStackTrace();
Log.i(TAG, "Second IOException");
}
}
}
But it seems stop at Socket socket = serverSocket.accept(); and doesn't show the log of TCPServerThread...socket.getInetAddress() = when the client try to connect to this Server.
DO I missing something for TCPServer ?
Is it mean the client doesn't connect to the Server when the code stop at Socket socket = serverSocket.accept(); ??
----------------------------EDIT----------------------------------------
Update the process.
The Server(Android Phone) open the WiFi-Hot-Spot, it also open the TCP-Server like the above code.
After Client connect to WiFi-Hot-Spot , the Client and the Server are in the same network.
The Client will get a IP address of gateway, and the Client try to connect to this IP address of gateway by TCP.
So the connection port and Server address seems correct for Client.
Your code is correct, but it seems that no one is connecting to your TCPserver.
To avoid this blocking situation on
Socket socket = serverSocket.accept();
you have to set the timeout option for your socket when you declare it
serverSocket.setSoTimeout(mTime);
;)

Android Socket Exception "socket is closed"

When I try to run a test composed of an echo server and an android client with the following code, I always get the exception msg "socket is closed". This code can simply send msg to server, and receive msg from server, but if you want to do both at the same time, it just doesn't work... I am very curious why it will lead to this kind of problem, and how should I fix it if I want it to be able to first send msg to echo server
and then receive msg from echo server?
// Server IP address
InetAddress serverIp;
// try to connect Server
try {
// set up server IP address
serverIp = InetAddress.getByName("192.168.17.1");
// set up port
int serverPort=12345;
// initiate socket connection
Socket clientSocket=new Socket(serverIp,serverPort);
BufferedOutputStream out = new BufferedOutputStream(clientSocket.getOutputStream());
out.write("Send From Android1111, stitch ".getBytes());
out.flush();
//wait to receive Server's msg
BufferedReader br =new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
total.toString();*/
// Display received msg with Toast
Toast.makeText(getApplicationContext(), br.readLine(), Toast.LENGTH_SHORT ).show();
//close connection
clientSocket.close();
// out.close();
// out = null;
} catch (IOException e) {
// display exception with Toast
Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show();
}
unfortunately, it still doesn't work ...I followed your instruction and modify the code to:
// set up Server IP address
serverIp = InetAddress.getByName("192.168.2.2");
// set up Server port
int serverPort=12345;
// initiate socket connection
Socket clientSocket=new Socket(serverIp,serverPort);
// open input and output stream
OutputStream out = clientSocket.getOutputStream();
InputStream in = clientSocket.getInputStream();
//send msg
out.write("Send From Android1111, bitch ".getBytes());
// receive msg from server
byte[] buffer = new byte[in.available()];
in.read(buffer);
String rMsg = new String(buffer);
Toast.makeText(getApplicationContext(), rMsg, Toast.LENGTH_LONG ).show();
//close input and output stream
in.close();
out.close();
//關閉連線
clientSocket.close();
} catch (IOException e) {
// 出錯後顯示錯誤訊息Toast
Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show();
}
for helper's convenience, here's the python written code for server part:
# Practice Echo Server Program written in Python
import socket
# host = '' means it binds to any available interface
host = ''
port = 12345
# socket() function returns a socket object whose methods implement the various socket system calls.
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# Bind the socket to address.
s.bind((host,port))
# Listen for connections made to the socket. The backlog argument specifies
# the maximum number of queued connections and should be at least 0;
# the maximum value is system-dependent (usually 5), the minimum value is forced to 0.
s.listen(5)
# Accept a connection. The socket must be bound to an address and listening for
# connections. The return value is a pair (conn, address) where conn is a new socket
# object usable to send and receive data on the connection, and address is the address
# bound to the socket on the other end of the connection.
conn, addr = s.accept()
print 'Connected by', addr
# Receive data from the socket. The return value is a string representing the data received.
# The maximum amount of data to be received at once is specified by bufsize. See the Unix
# manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.
# Note For best match with hardware and network realities, the value of bufsize should be
# a relatively small power of 2, for example, 4096.
while 1:
data = conn.recv(1024)
if not data: break
print 'received data is : ', repr(data)
conn.send(data)
conn.close()
I assume you are doing the right things in the wrong order. May be the server is too fast and when you are trying to read the response it is already received and gone.
Following the rules presented in the tutorial Reading from and Writing to a Socket
Open a socket
Open an input stream and output stream to the socket.
Read from and write to the stream according to the server's protocol.
Close the streams.
Close the socket.
Do you see the difference? First open Input and Output stream and then start sending your request.
I am sure that if you stick to this order it will work.
I had a similar issue, solved it by editing the gradle.properties file to allow for proxy connections. I added the foregoing lines as explained on https://github.com/facebook/react-native/issues/2726 by Nadeem Shaik
systemProp.http.proxyHost=proxyHost
systemProp.http.proxyPort=proxyPort
systemProp.https.proxyHost=proxyHost
systemProp.https.proxyPort=proxyPort
Your application needs INTERNET permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>

localhost server in android

I have created the local host server in android and i am trying to communicate with my ajax call.I successfully connected to the server but unable to receive response.xmlhttp status returns 0 only.if i created the server as the sepa
Ajax call
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
document.getElementById("myDiv3").innerHTML=xmlhttp.readyState+"";
// document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
if (xmlhttp.readyState==4)
{
document.getElementById("myDiv1").innerHTML=xmlhttp.status+"";
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
// document.getElementById("myDiv2").innerHTML="2";
}
xmlhttp.open("GET","http://localhost:8888/Server",true);
//xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
server code
try{
String fromclient;
String toclient;
ServerSocket Server = new ServerSocket (8888);
System.out.println ("TCPServer Waiting for client on port 8888");
while(true)
{
Socket connected = Server.accept();
System.out.println( " THE CLIENT"+" "+
connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED ");
PrintWriter outToClient =
new PrintWriter(
connected.getOutputStream(),true);
outToClient.write("<html><head>hai</head></html>");
connected.close();
}
}
catch(Exception e)
{
}
}
The term "localhost" is not correct at all here. "Development machine" or "host machine" would me more accurate.
Anyway, change:
xmlhttp.open("GET","http://localhost:8888/Server",true);
and use:
xmlhttp.open("GET","http://10.0.2.2:8888/Server",true);
Remember to check your firewall/iptables and all that stuff. I didn't check your code for any other error but this should do the trick regarding the connection.

Categories

Resources