Is it possible to connect two phones using socket programming?
I tried following code but it didn’t work
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();//Public function to get ip address to it is //working fine
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(8087);
} else {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
Yes, it is possible but I think the first thing you should do is read up on Java Socket programming as there are a few problems with your code that make me think you haven’t quite got a grasp of it yet. The main problems are:
ServerSocketnever accepts a connection and is therefore never actually ‘listening’.You will need to implement a client on one phone and a server on the other like @Deepak has shown.
Also, you may want to check out
AsyncTaskin this article for updating views from a non-UI thread (instead of a handler).Finally, make sure your app includes the
android.permission.INTERNETpermission inAndroidManifest.xml.