I have some trouble with the ObjectInputStream in an little android project. On my Laptop I have a Server running, which respondes an int to a String, which comes from my client (running on my andoid device).
Here is my Server:
ServerSocket socketmaker = new ServerSocket(30001);
Socket tSocket = socketmaker.accept();
ObjectInputStream in = new ObjectInputStream(tSocket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(tSocket.getOutputStream());
String text = "";
int hashed = 0;
text = (String) in.readObject();
System.out.print("The Client asks with \""+text+"\"");
hashed = hash(text);
out.writeUTF(String.valueOf(hashed));
System.out.print(" and we answer with the hash \""+hashed+"\"\n");
out.close();
in.close();
tSocket.close();
And here comes the app:
public void onClick(View v) {
String server = host.getText().toString();
int portNr = Integer.parseInt(port.getText().toString());
try {
Socket tSocket = new Socket(server, portNr);
ObjectOutputStream out = new ObjectOutputStream(tSocket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(tSocket.getInputStream());
String text = content.getText().toString();
out.writeObject(text);
int re = Integer.parseInt(in.readUTF());
Toast.makeText(ClientActivity.this, re, Toast.LENGTH_SHORT).show();
out.close();
in.close();
tSocket.close();
} catch(Exception e) {
//print ex here...
}
}
host, port, conent are EditText's and allow the client to put in the serverinfo.
I run the server on a console and it receives the text from the client and prints out:
The Client asks with "test" and we answer with the hash "48"
But then the app closes with an error. So the error has to be with the server sending the int and the app receiving it.But I also set the permissions in the Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I also tried it with:
writeObject(int) - Integer.parseInt(readObject())
writeObject(String) - readObject()
writeInt(int) - readInt()
but none of them worked.
So please help me, and excuse my bad english (non native). Thanks