我实际上想在Java Server和我的Android游戏之间编写TCP通信,以便将数据保存到数据库中。曾经有过全球排行榜。
我实际上现在正在编写服务器并且可以使用我编写的客户端连接到它,并希望稍后在Android中实现。 以下是客户的一些代码:
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();
}
}
服务器现在做的是获取第一行并根据值检查要执行的操作。在服务器上会发生这种情况:
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);
}
}
我将服务器端的所有内容记录到textarea并在服务器端实际获取:
我提交com.saveToDatabase("test", 2, 123651);
如果我以UTF的身份发送所有内容,我实际上也会得到一些惊人的东西:
希望你能帮助我,甚至可以告诉我这是否适用于android。非常感谢。 目前它没有正确传递字符串。
SAVE: Level: 1908 KP: 1702065249
Client disconnected: 0
答案 0 :(得分:2)
您的代码有太多问题。 你写了一个int(writeInt),但你在服务器上读取一个字节(读取)。 writeUTF也只是在线上放一个字符串,但是你读了一个带有新行的字符串。 使用DataInputStream读取相应的DataOutputStream。 还要在套接字之前关闭输出流。