Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket Programming with Python server and Android client

I want to setup a socket interface. PC side runs a very simple socket server written in Python to test the connection:

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 5000                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

An Android client application will connect to PC:

package com.example.androidsocketclient;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

    private Socket socket;

    private static final int SERVERPORT = 5000;
    private static final String SERVER_IP = "192.168.2.184";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        new Thread(new ClientThread()).start();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void onClick(View view) {
        try {
            EditText et = (EditText) findViewById(R.id.EditText01);
            String str = et.getText().toString();
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(str);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ClientThread implements Runnable {

        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                socket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

    }

}

However, I cannot establish a connection between PC and Android device. Any idea to fix this?

like image 455
yildizabdullah Avatar asked Mar 08 '14 15:03

yildizabdullah


3 Answers

You have to input ip adress and port number in your code there is not ip adress and port number where is it ?? just see below example:

public void connect() {
      new Thread(new Runnable(){

        @Override
        public void run() {
            try {

                client = new Socket(ipadres, portnumber);

                printwriter = new PrintWriter(client.getOutputStream(), true);
                printwriter.write("HI "); // write the message to output stream
                printwriter.flush();
                printwriter.close();
                connection = true;
                Log.d("socket", "connected " + connection);

                // Toast in background becauase Toast cannnot be in main thread you have to create runOnuithread.
                // this is run on ui thread where dialogs and all other GUI will run.
                if (client.isConnected()) {
                    MainActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            //Do your UI operations like dialog opening or Toast here
                         connect.setText("Connected");
                            Toast.makeText(getApplicationContext(), "Messege send", Toast.LENGTH_SHORT).show();
                        }
                    });
                                        }
            }
            catch (UnknownHostException e2){
                   MainActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        //Do your UI operations like dialog opening or Toast here
                        Toast.makeText(getApplicationContext(), "Unknown host please make sure IP address", Toast.LENGTH_SHORT).show();
                    }
                });

            }
            catch (IOException e1) {
                Log.d("socket", "IOException");
                MainActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        //Do your UI operations like dialog opening or Toast here
                        Toast.makeText(getApplicationContext(), "Error Occured"+ "  " +to, Toast.LENGTH_SHORT).show();
                    }
                });
            }

        }
    }).start();
}

just get input from user of ipadress and port number using edittext and you have to just copy and paste the code

Enjoy! if did not work post again here.

like image 155
Robokishan Avatar answered Sep 24 '22 08:09

Robokishan


As you haven't detailed if you're using either private or public IPs, it might be any of the following issues:

If you're using private connections, it's obvious it's not a router-firewall related problem as you are under the same net, so there are only a few possibilities:

  • There's nothing listening on that port on that IP on the server-side
  • There's a local firewall on the server-side that is blocking that connection attempt
  • You are not using WIFI so you're not under the same net.

You should make sure you can open that service some ther way, that would help you debugging where the culprit is. If you've already done this, I'd suggest using some debugging tool to trace TCP packets (I don't know either what kind of operating system you use on the destination machine; if it's some linux distribution, tcpdump might help; under Windows systems, WireShark might be useful).

If you're using public IPs, sum up a router blocking firewall, which means that this port might be closed/filtered on the server side, just open it.

All that assuming you have the android.permission.INTERNET permission in your AndroidManifest.xml file.

like image 28
nKn Avatar answered Sep 22 '22 08:09

nKn


You are running the server on socket.gethostname() and you are trying to connect the android app to "192.168.2.184".

Try running the server on this address

s = socket.socket()         
host = "192.168.2.184" 
port = 5000                
s.bind((host, port))
like image 32
Saya Avatar answered Sep 24 '22 08:09

Saya