I'm attempting to set up a client-server relationship between an android device (emulator) and my laptop. The socket seems to be set up correctly as data is transferred from the client to the server at first, but the program is getting stuck on the client side when trying to use ObjectInputStream to establish an input stream.
Here is the code used to setup the server on the laptop:
try{
providerSocket = new ServerSocket(6666);
connection = providerSocket.accept();
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
System.out.println("output stream established");
in = new ObjectInputStream(connection.getInputStream());
System.out.println("input stream established");
try{
message = (String)in.readObject();
System.out.println("client>" + message);
sendMessage("Thanks for the message!");
}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
}
}
catch(IOException ioException){
ioException.printStackTrace();
}
Here is the relevant code for the android device. The updatePhotos method is called when a certain button is pushed, you can see the button's text is changed to help spot where the code stops.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void updatePhotos(View view){
Button button = (Button)findViewById(R.id.button7);
try {
String msg = "Hello";
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
out.writeObject(msg);
out.flush();
button.setText("Establishing Input Stream");
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
button.setText("Input stream established");
msg = (String)in.readObject();
button.setText(msg);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
So the server program is run first, and then the android application is run on the emulator. The ClientThread starts when the first app activity starts and the socket connection is made successfully.
Next, I click the button and the programs run until the button text reads "Establishing Input Stream" and the Eclipse console reads:
output stream established
input stream established
client>Hello
server>Thanks for the message!
Clearly the program is stopping at the line that creates the ObjectInputStream for the client even though data is being sent to the client from the server. There are no error messages anywhere. What am I doing wrong here?