5

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?

4
  • 1
    "I cannot establish a connection between PC and Android device" is very vague. Is it giving an exception? If so, could you update your question with the LogCat? Commented Mar 8, 2014 at 15:30
  • 2
    PC probably has a firewall blocking incoming connections; Windows firewall or McAfee/Symantec/etc. Try turning those off and retesting. If that doesn't do it, it's harder to test both sides at once, see if you can prove one side works then the other. On the Android device can you open the web browser and go to http://192.168.2.184:5000/ and see if it will connect. It might even show your 'Thank you for connecting' message. If that works you know your client code is at fault, if that doesn't work you know your network connection or server code isn't right yet. Commented Mar 8, 2014 at 15:33
  • It connects to server when accessed by a web browser (192.168.2.184:5000) on Android device. Commented Mar 8, 2014 at 16:01
  • OK, now I can establish a connection. Commented Mar 8, 2014 at 16:08

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.