Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi I'm trying to connect 2 android device (without server in the middle, just directly like peer-to-peer) which are connected to internet(they are far apart) and send messages.
I thought its like normal socket programming, and connects via IP, seems not.

what I have done so far is this:
I have created 2 android projects, server(receiver) and client(sender) running in 2 separate devices
Both devices are connected to internet
found the IP of the device with server app running in (using whatismyip.com) and used it in client app code
but when I want to send a text from client to server, an exception happens in client printing Error3

this is my code:
server:

public class MainActivity extends Activity {

	   ServerSocket ss = null;
	   String mClientMsg = "";
	   Thread myCommsThread = null;
	   protected static final int MSG_ID = 0x1337;
	   public static final int SERVERPORT = 6000;

	   @Override
	   public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		TextView tv = (TextView) findViewById(R.id.TextView01);
		tv.setText("Nothing from client yet");
		this.myCommsThread = new Thread(new CommsThread());
		this.myCommsThread.start();
	   }

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

	   Handler myUpdateHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_ID:
				TextView tv = (TextView) findViewById(R.id.TextView01);
				tv.setText(mClientMsg);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	   };
	   class CommsThread implements Runnable {
		public void run() {
			Socket s = null;
			try {
				ss = new ServerSocket(SERVERPORT );
			} catch (IOException e) {
				e.printStackTrace();
			}
			while (!Thread.currentThread().isInterrupted()) {
				Message m = new Message();
				m.what = MSG_ID;
				try {
					if (s == null)
						s = ss.accept();
					BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
					String st = null;
					st = input.readLine();
					mClientMsg = st;
					myUpdateHandler.sendMessage(m);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	    }
	}





Client:



public class MainActivity extends Activity {

	   private Button bt;
	   private TextView tv;
	   private Socket socket;
	   private String serverIpAddress = "5.114.22.118";
	   // AND THAT'S MY DEV'T MACHINE WHERE PACKETS TO
	   // PORT 5000 GET REDIRECTED TO THE SERVER EMULATOR'S
	   // PORT 6000
	   private static final int REDIRECTED_SERVERPORT = 80;
	   
	   @Override
	   public void onCreate(Bundle savedInstanceState) {
	      super.onCreate(savedInstanceState);
	      setContentView(R.layout.activity_main);
	      bt = (Button) findViewById(R.id.myButton);
	      tv = (TextView) findViewById(R.id.myTextView);
	      
	      new Thread(new ClientThread()).start();
	      
	      bt.setOnClickListener(new OnClickListener() {
	         public void onClick(View v) {
	            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);
	               Log.d("Client", "Client sent message");
	            } catch (UnknownHostException e) {
	               tv.setText("Error1");
	               e.printStackTrace();
	            } catch (IOException e) {
	               tv.setText("Error2");
	               e.printStackTrace();
	            } catch (Exception e) {
	               tv.setText("Error3");
	               e.printStackTrace();
	            }
	         }
	      });
	   }
	   
	   class ClientThread implements Runnable {
		
		   @Override
	       public void run() {
			   try {
			         InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
			         socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
			      } catch (UnknownHostException e1) {
			         e1.printStackTrace();
			      } catch (IOException e1) {
			         e1.printStackTrace();
			      }
		   }
	   }
        
	}
Posted
Comments
Richard MacCutchan 6-Mar-15 12:47pm    
It's probably getting blocked by your firewall. BTW it is better if you list the errors that you receive so people can offer more suggestions.
mehdi_k 6-Mar-15 15:47pm    
thanks for you suggestion, one other thing is that I though pinging the device IP in cmd gives me respond, but when I ping the IP it's just timeout!!
Edit: I don't thing there is any firewall on my phone.
Richard MacCutchan 7-Mar-15 3:23am    
If it times out then that probably means that there is no route from your phone to the IP address you are trying to reach. And the destination address may well be blocked by a firewall somewhere.
mehdi_k 7-Mar-15 3:30am    
I am sure that my phone is connected to the internet, shouldn't it respond when you ping the IP? is there any chance the IP is wrong or something?
Richard MacCutchan 7-Mar-15 4:38am    
How have you determined that it is connected to the internet? How have you verified its IP address? You need to answer those questions before you can do anything else.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900