1

I have two Real Ip address 220.xx.xxx.xxx in my work place. I tried to make a simple java tcp server program and android tcp client program. The android client works fine when:

  1. Server and emulator program in the same pc.
  2. Server in one pc having real IP address emulator is in another pc with a real ip address.
  3. Server and emulator both within under private network within same pc or different pc or device.

does not work when:

  1. client is a smart phone having wifi or 3g network, and server have a real IP address on different network.
  2. client is an emulator running on wifi connected device, server have a real ip address.

So, how to connect to a Java TCP server socket having Public IP From Android Tcp Client Socket? I dont think pasting code is really necessary here. However if some one ask I can provide. According to my search on the internet some people provide suggestion to configuring the router on the server side. this seems to me little bit annoying. if I run a websever it can be accessed from anywhere any place. code included here: Server side:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.*;

public class Server {

    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static OutputStreamWriter outputStreamWriter;
    private static BufferedWriter bufferedWriter;
    private static PrintWriter printWriter;
    private static String message;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            System.out.println(InetAddress.getLocalHost());
            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
                System.out.println("connection initiated");

                DataInputStream din = new DataInputStream(clientSocket.getInputStream());

                DataOutputStream dout= new DataOutputStream(clientSocket.getOutputStream());

                String msg = din.readUTF();
                System.out.println(msg);

                dout.writeUTF("hello from server");
                System.out.println("sent to client");



                clientSocket.close();

            } catch (IOException ex) {
                System.out.println("Problem in message reading "+ex);
            }
        }
    }

}

Client Side:

package com.example.client;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
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 {

 TextView textResponse;
 EditText editTextAddress, editTextPort; 
 Button buttonConnect, buttonClear;

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

  editTextAddress = (EditText)findViewById(R.id.address);
  editTextPort = (EditText)findViewById(R.id.port);
  buttonConnect = (Button)findViewById(R.id.connect);
  buttonClear = (Button)findViewById(R.id.clear);
  textResponse = (TextView)findViewById(R.id.response);

  buttonConnect.setOnClickListener(buttonConnectOnClickListener);

  buttonClear.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    textResponse.setText("");
   }});
 }

 OnClickListener buttonConnectOnClickListener = 
   new OnClickListener(){

    @Override
    public void onClick(View arg0) {
     MyClientTask myClientTask = new MyClientTask(
       editTextAddress.getText().toString(),
       Integer.parseInt(editTextPort.getText().toString()));
     myClientTask.execute();
    }};

 public class MyClientTask extends AsyncTask<Void, Void, Void> {

  String dstAddress;
  int dstPort;
  String response = "";

  MyClientTask(String addr, int port){
   dstAddress = addr;
   dstPort = port;
  }
  private PrintWriter printwriter;
  private InputStreamReader inputStreamReader;
  private BufferedReader bufferedReader;
  @Override
  protected Void doInBackground(Void... arg0) {

   Socket socket = null;

   try {
    socket = new Socket(dstAddress, dstPort);

    DataInputStream din = new DataInputStream(socket.getInputStream());
    DataOutputStream dout = new DataOutputStream(socket.getOutputStream());

    dout.writeUTF("hello from client");

    response="sent to serve;r";

    String msg = din.readUTF();
    response+=msg;

    socket.close();

   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    response = e.toString();
   }
   return null;
  }

  @Override
  protected void onPostExecute(Void result) {
   textResponse.setText(response);
   super.onPostExecute(result);
  }

 }

}
biborno
  • 175
  • 1
  • 11
  • What do you consider to be a 'real ip'? Are you mixing up the internet ip of your router with the local ip your computer gets from the router? – greenapps Mar 22 '15 at 23:44
  • It is a pitty that you did not place the question in your post. An Android client can connect with a server on the internet if the client has internet connection too and uses the internet ip of the server. That's all. In your 'does not work 1' you mention wifi and 3G at the same time. That is not possible. Threat them differently as they are different. – greenapps Mar 22 '15 at 23:57
  • "What do you consider to be a 'real ip'?" --- answer: public ip address: which accessible from anywhere in the internet if a webserver runs on it. "Are you mixing up the internet ip of your router with the local ip your computer gets from the router? " --- answer: No I m not. I also mentioned the ip address starting 3 digits. its not local or private ip address. I m pretty sure i didnt mixed it up – biborno Mar 23 '15 at 01:45
  • "It is a pitty that you did not place the question in your post." -- Edited Now. Doesn't work section pretty much explain the problem. Didnt think that some people might have problem to understand. " – biborno Mar 23 '15 at 01:57
  • "An Android client can connect with a server on the internet if the client has internet connection too and uses the internet ip of the server."-- what does it mean? uses the internet ip of the server? I made that pretty clear android client and server are on different network when It did not work. Read the question again if u don't understand. if server has real Ip address and android client is in wifi or 3g network, how come they use same internet? – biborno Mar 23 '15 at 02:02
  • " In your 'does not work 1' you mention wifi and 3G at the same time. That is not possible. Threat them differently as they are different" -- Please Read the question twice if u dont understand and give it a minute before placing arbitrary comments. "client is a smart phone having wifi or 3g network," did u see the "OR" in the statement? how did u find that I told wifi and 3g at the same device same time? – biborno Mar 23 '15 at 02:06
  • If you're asking a coding question you need to post the code. If you're not, you're off topic here. – user207421 Mar 23 '15 at 02:11
  • @biborno: have you seen my answer ? – Yash Sampat Mar 25 '15 at 08:40
  • @ZygoteInit Yes! thank you very much ! Can u please provide me with a reference? – biborno Mar 25 '15 at 10:36
  • @biborno: i will look for some nice references and add them. meanwhile, can you please mark my answer as correct and upvote it ? Thanks :) – Yash Sampat Mar 25 '15 at 13:17
  • @ZygoteInit: I was actually waiting for references. I tried to search and waited to look if someone else gives his opinion. I upvoted your answer the moment I saw it. I liked the answer :). However one person gave you down vote and also commented there. however the comment is removed now. but his downvote is still there. For now I will mark the answer as accepted. – biborno Mar 27 '15 at 09:01
  • @biborno: sorry for the late reply. i've added the references, please see edited answer :) – Yash Sampat Mar 27 '15 at 09:50

2 Answers2

1

For TCP connections to work on a real device, you need to provide the URL of a publicly hosted domain. A localhost or a local network URL works only with an emulator on a PC on the same local network.

References:

1. Emulator Networking.

2. How to connect to my http://localhost web server from Android Emulator in Eclipse

3. Accessing localhost:port from Android emulator

4. Calling web service from android device

5. Connect an Android Device To a Web Service on Local Host

6. How can I access my localhost from my Android device?

7. How to browse localhost on android device?

Community
  • 1
  • 1
Yash Sampat
  • 30,051
  • 12
  • 94
  • 120
  • Sorry! I just successfully run the program by changing port number from 4444 to 6667. Although I dont know why because on 4444 it only worked on local network. – biborno Mar 27 '15 at 15:19
1

I just changed the port number from 4444 to 6667 and It worked on everywhere now. I dont think port 4444 was used on somewhere else because the program works on local network

biborno
  • 175
  • 1
  • 11