Gene
Gene

Reputation: 173

Android: "Socket Not Connected" Exception

I'm having some issues with sending data from an Android client to a desktop server over TCP via wifi. The emulator works fine, but on the actual phone, the connection cannot be established. A "socket not connected" exception was thrown.

I have attached my code below. Any help please? Many thanks!

// CODE inside an Activity

public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
   case R.id.send:
           sendMessage();
           return true;
   /// ...other items
   }
}

private void sendMessage() {
   String serverAddr = "18.xxx.xx.xxx";
   Socket socket = null;
   try {
           socket = new Socket(serverAddr, 4444);  // EXCEPTION HAPPENS HERE
   } catch (Exception e) {
           //show exception on screen
   }

   String message = "some message";
   try {
           PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
           out.println(message);
   } catch (Exception e) {
           //show exception on screen
   } finally {
           socket.close();
   }
}

Upvotes: 1

Views: 2425

Answers (3)

Mohamed Gamal
Mohamed Gamal

Reputation: 1348

Server Address Should be your Server local address in the network . Also you need to configure router "PORT FORWORDING" to send all packets from port 4444 and forward it to your server local ip. Also both phone and server pc should be connected to the same WiFi network.

Upvotes: 0

ajay
ajay

Reputation: 93

You can go through Exception handling in java using: - http://source.android.com/source/code-style.html#java-language-rules.Hope you can find solution.

Upvotes: 0

Sohil Himanish
Sohil Himanish

Reputation: 21

Your serverAddr should not be a string but be a InetAddr . Use InetAddr.getByName("18.x.x.x")

Upvotes: 2

Related Questions