Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement