0

Here is my code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_server);
    serverStatus = (TextView) findViewById(R.id.server_status);

    SERVERIP = getLocalIpAddress();

    Thread fst = new Thread(new ServerThread());
    fst.start();
}

public class ServerThread implements Runnable {

    public void run() {
        try {
            if (SERVERIP != null) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Listening on IP: " + SERVERIP);
                    }
                });
                serverSocket = new ServerSocket(SERVERPORT);
                while (true) {
                    // listen for incoming clients
                    Socket client = serverSocket.accept();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            serverStatus.setText("Connected.");
                        }
                    });

                    try {
                        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                        String line = null;
                        while ((line = in.readLine()) != null) {
                            Log.d("ServerActivity", line);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    // do whatever you want to the front end
                                    // this is where you can be creative
                                }
                            });
                        }
                        break;
                    } catch (Exception e) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
                            }
                        });
                        e.printStackTrace();
                    }
                }
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Couldn't detect internet connection.");
                    }
                });
            }
        } catch (Exception e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    serverStatus.setText("Error");
                }
            });
            e.printStackTrace();
        }
    }
}

// gets the ip address of your phone's network
private String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) { 
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(inetAddress.getHostAddress().toString());
                    if(isIPv4)
                    return inetAddress.getHostAddress().toString(); }
            }
        }
    } catch (SocketException ex) {
        Log.e("ServerActivity", ex.toString());
    }
    return null;
}

@Override
protected void onStop() {
    super.onStop();
    try {
         // make sure you close the socket upon exiting
         serverSocket.close();
     } catch (IOException e) {
         e.printStackTrace();
     }
}

Client Side

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

    serverIp = (EditText) findViewById(R.id.server_ip);
    connectPhones = (Button) findViewById(R.id.connect_phones);
    connectPhones.setOnClickListener(connectListener);
}

private OnClickListener connectListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        if (!connected) {
            Log.e("Clicked", "Yes");
            serverIpAddress = serverIp.getText().toString();
            if (!serverIpAddress.equals("")) {
                Thread cThread = new Thread(new ClientThread());
                cThread.start();
            }
        }
    }
};

public class ClientThread implements Runnable {

    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
            connected = true;
            while (connected) {
                try {
                    Log.d("ClientActivity", "C: Sending command.");
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                .getOutputStream())), true);
                        // where you issue the commands
                        out.println("Hey Server!");
                        Log.d("ClientActivity", "C: Sent.");
                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }
            }
            socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }
}
}

I have used that between two emulators the server is showing that it is listening on 10.0.2.15

But when i go for connection it does not connect

Thers is no error in logcat also i have checked between two physical devices running Android 4.0 with 3G internet Just want to push the android devices running server activity from client activity so that i can perform a action when client send something.

Nothing happens when i click connect button

Permissions:

  <uses-permission android:name="android.permission.INTERNET" />
Punit
  • 667
  • 1
  • 7
  • 17
  • This will not work between 3g devices as the mobile providers will block the incoming connection. – Chris Stratton Mar 10 '14 at 14:32
  • Then what to do to communicate between two devices. Also it is not working on emulators. – Punit Mar 10 '14 at 14:37
  • I want to send a message without using server between them – Punit Mar 10 '14 at 14:38
  • How can i push a string to another device using android device? – Punit Mar 10 '14 at 14:39
  • You cannot do this via 3g without an intermediate server or special policy exemptions from the mobile network providers. – Chris Stratton Mar 10 '14 at 14:55
  • But how can server send msg to android device if ISP blocks incoming connections – Punit Mar 10 '14 at 14:57
  • The device makes an **outgoing** connection to the server. But with two devices trying to talk directly, only one could be outgoing and the other would have to be incoming, and that is the part that gets blocked by its carrier. So you need a server to accept two incoming connections and shuttle data between them. – Chris Stratton Mar 10 '14 at 14:59
  • Yes i have php server to which the application connects but how server automatically push the data to 2nd device when 1st device send something? – Punit Mar 10 '14 at 15:02
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/49410/discussion-between-punit-and-chris-stratton) – Punit Mar 10 '14 at 15:02

1 Answers1

0

There's a demo for Bluetooth Chat and WiFi Direct in Android SDK. So you should use Bluetooth or WiFi. I don't think that you can acvhieve direct connection using cellular network.