(Socket Closed) exception in Android when receiving a string from python server - android

I am trying to communicate between my python server and android client. I setup a connection between them and that works fine, then i send a string to the server from my android app and that works fine as well. The server receives the string and then sends a string in reply to the client but at that time the my code catches an exception. The exception is "Socket Closed" and I've set the ex.getMessage() to my textView to see it.
I've set the port number 12345 for it and got a domain ijaw.ddns.net from noip.com which is live.
I've gone through stackover flow many times but cant seem to find the problem. PLease help me with this.
This is my android client code.
package com.example.ozair.ports;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
//Java imports
//import android.util.Log;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MainActivity extends Activity{
private Button ligar;
private EditText text1;
private TextView text2;
static Socket cSocket;
static PrintWriter out;
static BufferedReader in;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ligar = (Button) findViewById(R.id.Ligar);
text1 = (EditText) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
ligar.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
connect();
}
});
}
public void connect() {
cSocket = null;
out = null;
in = null;
dis = null;
try{
cSocket = new Socket("ijaw.ddns.net",12345);
out = new PrintWriter(cSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
final String message = text1.getText().toString();
out.write(message + "\r");
out.flush()
out.close();
char[] buff = new char[1024];
int i = in.read(buff);
in.close();
out.close();
cSocket.close();
text2.setText(buff.toString());
//cSocket.close();
}
catch (IOException ex) {
//Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
text2.setText(ex.getMessage());
}
}
//
}
And this is my python server code.
#!/usr/bin/python # This is server.py file
import time
import threading
import _thread
import socket # Import socket module
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# Create a socket object
s.settimeout(1000)
host = '' # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
BUFFER_SIZE = 1024
def clientthread(c):
print ('Got connection from', addr)
threadid=threading.current_thread().name
print(threadid)
data = c.recv(BUFFER_SIZE).decode()
#time.sleep(1)
c.sendall(b'Thank you for connecting')
#u = unicode(data, "utf-8")
print("received [%s]" % data)
c.close()
#print ("received data: ", data)
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
_thread.start_new_thread(clientthread,(c,))
#print 'Got connection from', addr
#c.send('Thank you for connecting')
c.close() # Close the connection
sock.close()

Related

Android Studio to SQL Server - the SQL data is not displaying

package com.example.connectandroid_sql;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionHelper {
String uName, pass, iP, port, database;
#SuppressLint("NewAPI") //This syntax will be able to stop the app from crashing
public Connection connectionClass() {
iP = "136.158.28.124";
database = "ExperimentTable";
uName = "sa";
pass = "admin";
port = "1433";
Connection connection = null;
String ConnectionURL = null;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc;jtds:sqlserver://" + iP + ":" + port
+ ";" + "databasename =" + database + ";user=" + uName
+ ";password= " + pass+ ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (Exception ex){
Log.e("Error",ex.getMessage());
}
return connection;
}
}
The SQL data is not displaying, the error I kept receiving is the
"E/Error: net.sourceforge.jtds.jdbc.Driver")
Here is my Connector Syntax
package com.example.connectandroid_sql;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
Connection connect;
String ConnectionResult ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getTextFromSQL(View v){
TextView tx1 = findViewById(R.id.textView);
TextView tx2 = findViewById(R.id.textView2);
try{
ConnectionHelper connectionHelper = new ConnectionHelper();
connect = connectionHelper.connectionClass();
if (connect != null){
String query = "Select * from ExperimentTable";
Statement st = connect.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()){
tx1.setText(rs.getString(2));
tx2.setText(rs.getString(3));
}
}
else{
ConnectionResult = "Check Connection";
}
}
catch (Exception ex){
Log.e("Error", ex.getMessage());
}
}
}
I did create a new port "1433", I did install an older version of the JDBC Driver.
There are a few more errors that says
Invalid File Path for libcolorx-loader.so
E/Perf: perftest packageName : com.example.connectandroid_sql App is allowed to use Hide APIs
But overall it runs all good, the only problem that I am encountering is that it does not display the data.

Python server Android client

I want to make simple communication between python server running on a pc and android client. I tested it with python client program and it worked well but in android it's not working .Here is my python server side code:
import socket
import sys
HOST = '192.168.1.102'
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'socket created'
#Bind socket to Host and Port
try:
s.bind((HOST, PORT))
except socket.error as err:
print 'Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1]
sys.exit()
print 'Socket Bind Success!'
#listen(): This method sets up and start TCP listener.
s.listen(10)
print 'Socket is now listening'
while 1:
conn, addr = s.accept()
print 'Connect with ' + addr[0] + ':' + str(addr[1])
buf = conn.recv(64)
print buf
s.close()
This is my MainActivity.java code :
package com.example.tjsiledar.sendmessage;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.editText);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new SendMessage().execute(editText.getText().toString());
editText.getText().clear();
}
});
}
}
and this is my SendMessage.java code :
package com.example.tjsiledar.sendmessage;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class SendMessage extends AsyncTask<String, Void, Void> {
private Exception exception;
#Override
protected Void doInBackground(String... params) {
try {
try {
Socket socket = new Socket("192.168.1.102",8888);
PrintWriter outToServer = new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()));
outToServer.print(params[0]);
outToServer.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
this.exception = e;
return null;
}
return null;
}
}

http Response android studio cant connect to xamp

my httpresponse can connect to xamp.. it have failed to conncet server !! output with this code
please help me to get solution..
package com.zul.app.login;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.h
ttp.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
private EditText txtUser;
private EditText txPass;
private EditText txStatus;
private Button btnLogin;
private String url ="http://192.168.42.175/loginandroid/cekuser.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtUser = (EditText) findViewById(R.id.user);
txPass = (EditText) findViewById(R.id.pass);
txStatus = (EditText) findViewById(R.id.statuslog);
btnLogin =(Button) findViewById(R.id.btlogin);
btnLogin.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
url = "http://192.168.42.175/loginandroid/cekuser.php";
url +="?user="+txtUser.getText().toString()+"&pass="+txPass.getText().toString();
getRequest(txStatus,url);
};
});
};
this is my http respon:
public void getRequest(EditText txtResult, String Surl){
Log.d("getRequest",Surl);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Surl);
try{
HttpResponse response = client.execute(request);
txtResult.setText(request(response));
}catch (Exception e){
txtResult.setText("Failed Conect To Server!!");
};
};
private String request(HttpResponse response) {
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line+"\n");
}
in.close();
result = str.toString();
}catch (Exception e){
result="error";
};
return result;
}
};
ihave permission with
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
if i run this project i dont have error but can't connect to server or failed to acces my localhost
i have php file with this link loginandroid/cekuser.php
if i use browser in android i can connect to xamp but if i use my project i cant connect
result:
failed to connect server
logcat :
08-11 10:50:36.231 19556-19556/com.zul.app.login D/getRequest: http://192.168.42.175/loginandroid/cekuser.php?user=&pass=
08-11 10:50:36.256 19556-19556/com.zul.app.login I/System.out: main calls detatch()

Client Socket problems on Android

package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
new Incomingdata().execute();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
private class Incomingdata extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params)
{
setMyIp(ipaddress.getText().toString());
try
{
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
while(s.isConnected())
{
String input =r.nextLine();
System.out.println(""+input);
}
in.close();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
So this is where i am, i can flush data out but can not seem to receive it back in from the server i am fairly new at this and have got help in the past from this site. I am really stuck and running out of time
Any help would be great
And Thank you
There are two different types of Socket, one is used for connecting to a host, and the other one is used to listen for connections. What you want to do is before trying to connect, make a ServerSocket that listens to incoming connections to a specific port number and wait for a new connection, as such:
ServerSocket serverSocket = new ServerSocket(2000);
Socket s = serverSocket.accept();
This should be done in your AsyncTask before trying to connect to it (accept() is blocking so it will wait for an incoming connection). So, changing the following two lines with the above and calling the AsyncTask before trying to connect to it should do the trick:
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);

read cookies httpurlconnection android

I want to read all cookies from the server but I get the following error:
java.lang.IllegalStateException: Connection already established
How can I read the cookies before connecting? I tried putting the cookie read code before defining the connection but It does not work until I define the connection which establishes the connection which prevents me from reading cookies...
Any help please?
Here's my code:
package com.example.read;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
List<String> cookies = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(l);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
View.OnClickListener l = new View.OnClickListener() {
public void onClick(View v) {
EditText edt = (EditText)findViewById(R.id.editText1);
if(!edt.getText().toString().equals("")){
readData(edt.getText().toString());
}
}
};
void readData(String text){
URL url;
HttpURLConnection conn;
DataOutputStream out;
DataInputStream in;
try{
url = new URL("http://"+text);
conn = (HttpURLConnection)url.openConnection();
if(cookies==null){
conn.getHeaderField("Set-Cookie");
}
if(cookies!=null){
for(String cookie : cookies){
conn.setRequestProperty("Cookie", cookie);
}
}
conn.setDoOutput(true);
String post = "mobile_app="+URLEncoder.encode("1","UTF-8");
out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(post);
out.flush();
out.close();
in = new DataInputStream(conn.getInputStream());
String line = "";
String data = "";
while((line=in.readLine())!=null){
data+=line;
}
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(data);
} catch(Exception e){
System.out.println(e);
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(e.toString());
}
}
}
Your question sounds a bit strange. As a client you set the cookies before establishing the connection - if you know them. The Set-Cookie header, the server returns, can only be read as soon as the answer of the server has been returned. Then of course it's to late to set any client-cookies :-)
In other words: You simply cannot read cookies from the server before you send the request.
The server sends "Set-Cookie" headers, and afterwards clients send these cookies with every following request. So you can set your "Cookie" headers only from the second request onwards.

Categories

Resources