最近我完成了我的第一个客户端-服务器项目。它实际上很酷,但我有一个小问题。没有消息,但我想要带有完整名称和密码字段的 JSON。我正在将GSONjar 库用于JsonObject.我的服务器public class Server extends Thread {private static final int port = 8607;protected static String server_IP;public static void main(String[] args) { try { InetAddress iAddress = InetAddress.getLocalHost(); server_IP = iAddress.getHostAddress(); System.out.println("Server IP : " + server_IP); } catch (UnknownHostException e){ } try { //Server ServerSocket serverSocket = new ServerSocket(port); System.out.println("Server has started"); //Accepting client System.out.println("Waiting"); Socket socket = serverSocket.accept(); System.out.println("Client has been added"); //Send message to client BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); bw.write("Connection accepted"); bw.newLine(); bw.flush(); //receive json from client BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String json_string = br.readLine(); JsonParser jsonParser = new JsonParser(); JsonObject user = jsonParser.parse(json_string).getAsJsonObject(); System.out.println("JSON: " +user.toString()); } catch (IOException e) { e.printStackTrace(); } }}我的服务器控制台Server IP : 192.168.123.2Server has startedWaitingClient has been addedJSON: {"name":""}Process finished with exit code 0
1 回答
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
你的问题在这里:
name = editName.getText().toString();
password = editPassword.getText().toString();
当您还没有机会在字段中输入任何文本时,您已经在方法中分配了name和password变量onCreate()。它们将永远是空的。
您应该做的是将这两行移动onClick(View)到点击侦听器的方法中。像这样:
send_todata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
name = editName.getText().toString();
password = editPassword.getText().toString();
new SendDataToServer().execute(name, password);
}
});
这样,您将分配 2 个变量,name并且password仅当您单击按钮时。那时,您可能会在 2 个输入字段中找到一些内容。
添加回答
举报
0/150
提交
取消