Python server Android client - android

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;
}
}

Related

Simple Client Server Application android

Hello I am trying to write simple client-server application in android.Here is my code for the client.
package com.sudarshan.client;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
messsage = textField.getText().toString(); // get the text message on the text field
textField.setText(""); // Reset the text field to blank
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
}
});
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
client = new Socket("10.0.2.2", 4444); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
Here is the code for server
package com.sudarshan.server;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
The server code crashes.It gives a error as "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sudarshan.server/com.sudarshan.server.MainActivity}: android.os.NetworkOnMainThreadException".
What am i doing wrong?
Solved.
"android.os.NetworkOnMainThreadException" means that Network related tasks are not to be done on main thread directly ie. Activity Class.So, need to make a thread under main thread then do the work.

Android Programme and Python programme WIFI server communication

I'm creating an an Android Application which connects to Python Server and send UP and DOWN command and a Python code response like: light is ON and Light is Off.
Although I add a button to Android application which sends data to Python and a Python server sends back some string or a function to the Android app which shows up in Android TextView (I need to run a function on Raspberry and get the result back to Android in textView).
enter code here
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
Button btnUp;
Button btnDown;
Button rButton;
EditText txtAddress;
Socket myAppSocket = null;
public static String wifiModuleIp = "";
public static int wifiModulePort = 0;
public static String CMD = "0";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnUp = (Button) findViewById(R.id.btnUP);
btnDown = (Button) findViewById(R.id.btnDown);
rButton = (Button) findViewById(R.id.rButton);
txtAddress = (EditText) findViewById(R.id.ipAddress);
btnUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getIPandPort();
CMD = "UP";
Soket_AsyncTask cmd_increase_servo = new Soket_AsyncTask();
cmd_increase_servo.execute();
}
});
btnDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getIPandPort();
CMD = "DOWN";
Soket_AsyncTask cmd_decrease_servo = new Soket_AsyncTask();
cmd_decrease_servo.execute();
}
});
rButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getIPandPort();
CMD = "VIEW";
Socket_Received cmd_received_pi = new Socket_Received();
cmd_received_pi.execute();
}
});
}
public void getIPandPort() {
String iPandPort = txtAddress.getText().toString();
String temp[] = iPandPort.split(":");
wifiModuleIp = temp[0];
wifiModulePort = Integer.valueOf(temp[1]);
//Log.d("MYTEST","IP String" +iPandPort);
//Log.d("MY TEST","IP:"+wifiModuleIp);
// Log.d("MY TEST","PORT"+wifiModulePort);
}
public class Soket_AsyncTask extends AsyncTask<Void, Void, Void> {
Socket socket;
protected Void doInBackground(Void... params) {
try {
InetAddress inetAdress = InetAddress.getByName(MainActivity.wifiModuleIp);
socket = new java.net.Socket(inetAdress, MainActivity.wifiModulePort);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeBytes(CMD);
dataOutputStream.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public class Socket_Received extends AsyncTask<String, Void, Void> {
ServerSocket cScoket;
Socket socket;
//public TextView textView;
private DataInputStream in;
#SuppressLint("WrongThread")
protected Void doInBackground(String... params) {
try {
cScoket = new ServerSocket(MainActivity.wifiModulePort);
socket = cScoket.accept();
in = new DataInputStream(socket.getInputStream());
InputStreamReader reader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(reader);
final TextView textView = (TextView)findViewById(R.id.txtView);
textView.setText(br.toString());
socket.close();
in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
My Python code here:
enter code here
import lighton
from socket import *
from time import ctime
import time
lighton.setUP()
ctrCmd = ['UP','DOWN','VIEW']
HOST = ''
PORT = 5555
BUFSIZE = 1024
ADDR = (HOST,PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
tcpCliSock,addr = tcpSerSock.accept()
time.sleep(.05)
data = ''
data = tcpCliSock.recv(BUFSIZE).decode()
if not data:
print("there is no data")
break
if data == ctrCmd[0]:
lighton.ledOn()
if data == ctrCmd[1]:
lighton.ledOff()
if data == ctrCmd[2]:
r="hello world"
tcpCliSock.send(r.encode())
tcpSerSock.close();
My Python light on class code here:
import time
def setUP():
print("Setting up...")
def ledOn():
print("led is on")
def ledOff():
print("led is off")
if __name__ == '__main__':
setup()

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

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()

AsyncTask unfortunately stops on second execution

I'm trying to get strings from my Arduino with my Android phone, everything goes well except for when I press my updatebutton the second time, it unfortunately stops.
I can't seem to track the problem and I ran out of options so I'm asking for help to you guys now.
package com.TRY.udp2;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private String rcvStr, serverIP="192.168.0.15";
private TextView textLog;//Log for outputs
private EditText textMsg;
Button updateButton;//(dis)connect Button
Boolean connected=false;//stores the connectionstatus
DataOutputStream dataOutputStream = null;//outputstream to send commands
Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button updateButton = (Button) findViewById(R.id.updateButton);
textMsg = (EditText) findViewById(R.id.textMsg);
textLog = (TextView) findViewById(R.id.textLog);
updateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String textlogMsg = textMsg.getText().toString();
new synchTask().execute(textlogMsg);
}
});
}
private class synchTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String msg=params[0].toString();
InetAddress toAddress = null;
try
{
toAddress = InetAddress.getByName(serverIP);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
int port=5000;
DatagramSocket dtSocket = null;
try
{
dtSocket = new DatagramSocket(port);
}
catch (SocketException e1)
{
e1.printStackTrace();
}
byte[] dataBytes = msg.getBytes();
DatagramPacket sndPacket = new DatagramPacket(dataBytes, dataBytes.length, toAddress, port);
try
{
dtSocket.send(sndPacket);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
byte[] rcvData = new byte[1024];
DatagramPacket rcvPacket = new DatagramPacket(rcvData, rcvData.length);
dtSocket.receive(rcvPacket);
rcvStr = new String(rcvPacket.getData());
}
catch (IOException e)
{
e.printStackTrace();
}
return rcvStr;
}
protected void onPostExecute(String result) {
textLog.setText(rcvStr);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and if there's a better way of getting strings from arduino please help out.
You probably need to close dtSocket at the end of doInBackground(). Otherwise you will try to create a socket on a bound port when you execute it the second time.

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);

Categories

Resources