I actually want to write a TCP communication between a Java Server and my Android game, to save data to a database. Used to have a Global leadboard.
I actually wrote the server right now and can connect to it with a client i wrote and want to implement later in Android.
Here is some code from the Client:
public void saveToDatabase(String name , int level, int killpoints){
try {
Socket soc = new Socket("localhost", PORT);
DataOutputStream out = new DataOutputStream(soc.getOutputStream());
DataInputStream in = new DataInputStream(new BufferedInputStream(soc.getInputStream()));
//to call the save statement!
out.writeInt(0);
//give the stuff
out.writeUTF(name);
out.writeInt(level);
out.writeInt(level);
//close it
out.close();
in.close();
soc.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
}
What the server now does is it get the first line and checks what to do depending on the value. At the Server this happens:
public void run() {
try {
DataOutputStream out = new DataOutputStream (socket.getOutputStream());
// DataInputStream in = new DataInputStream(new InputStreamReader(
// socket.getInputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
Server.textArea.setText(Server.textArea.getText()+"Client connected: "+ clientNumber+ "\n");
int firstLine = in.readInt(); //get first line for switch
switch (firstLine) {
case 0:
// getting the whole objekt for the database in own lines!
String name = in.readUTF();
int level = in.readInt();
int kp = in.readInt();
Server.textArea.setText(Server.textArea.getText() + "SAVE: "
+ name + " Level: " + level + " KP: " + kp + "\n");
// Server.textArea.setText(Server.textArea.getText() + "SAVE called\n");
break;
case 1:
// else if return the top10
Server.textArea.setText(Server.textArea.getText()
+ "Return top10\n");
// outp.write("asdf string");
break;
default:
break;
}
out.close();
in.close();
socket.close();
Server.textArea.setText(Server.textArea.getText()
+ "Client disconnected: "+ clientNumber + "\n");
} catch (Exception e) {
System.out.println("IO error " + e);
}
}
I log everything on serverside to a textarea and acutally get this on serverside:

I commit com.saveToDatabase("test", 2, 123651);
If i sent everything as UTF i actually get also some strage stuff:
Hope you can help me out or even can tell me if this would work with android too. Thanks alot.
At the moment it does not transfare the string correct.
SAVE: Level: 1908 KP: 1702065249
Client disconnected: 0
Your code has too many issues.
You write an int (writeInt) but you read a byte (read) on the server.
Also writeUTF puts just a string on the wire but you read a string with a new line.
Use DataInputStream to read the corresponding DataOutputStream.
Also close the output stream before the socket.