简体   繁体   中英

How to connect to a Java TCP server socket having Public IP From Android Tcp Client Socket?

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

 }

}

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM