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.xx开发者_运维百科x";
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();
}
}
Your serverAddr should not be a string but be a InetAddr . Use InetAddr.getByName("18.x.x.x")
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.
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.
精彩评论