0

我有一个在 android 设备上运行的套接字服务器。然后从客户端我向服务器发送一个字符串,服务器返回相同的字符串(回显服务器)。我想做的事情是也获取一些其他字符串,而不仅仅是我发送的字符串。这是服务器代码:

boolean finished = false;   
try {
  DataInputStream in = new DataInputStream(client.getInputStream());
  PrintStream out = new PrintStream(client.getOutputStream());                                
  // Print a message:
  System.out.println("Client from : " + client.getInetAddress() + " port " + client.getPort());
  // now get the input from the socket...
  while(!finished) {
    String st = in.readLine();
    // Send the same back to client
    if (st.equals("hello")) {
      cur = dbHelper.getRandomQuestion();
      String question = cur.getString(cur.getColumnIndex("QUESTIONS"));
      String answer1 = cur.getString(cur.getColumnIndex("ANSWER1"));
      String answer2 = cur.getString(cur.getColumnIndex("ANSWER2"));
      String answer3 = cur.getString(cur.getColumnIndex("ANSWER3"));
      String answer4 = cur.getString(cur.getColumnIndex("ANSWER4"));
      out.println(question);                                        
    }                                    
    out.println(st);

这是客户端代码:

InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: SENDING...");
Socket socket = new Socket(serverAddr, 5000);
System.out.println("Connected to " + socket.getInetAddress() + ":" + socket.getPort());
connected = true;
while(connected) {
  try {                         
    BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );                        
    PrintStream out = new PrintStream(socket.getOutputStream());                                            
    out.println(data.getText());                                 
    line = in.readLine();  // read server
    System.out.println("Echo: " + line);
    handler.post(updateUI); // here i change a textview to show the echoed string
    in.close();  // Close stream
    out.close();
  } catch (Exception e) {
    Log.e("ClientActivity", "S: Error", e);                             
  }

  connected = false;
}

我也想返回 answer1,answer2,asnwer3,answer4。我怎么能那样做?

4

1 回答 1

1

您正在处理 Strins,所以我建议使用 readUTF() 和 writeUTF()。关键是您一次只能发送一个字符串。如果您想发送更多字符串,您必须创建一个字符串并在字符串之间放置一种间隔符。

当我写类似的东西时,我使用换行符作为分隔符并按以下方式格式化我的字符串:

字符串 1 + 空格键 + 字符串 2 + 空格键 + 字符串....

On the other side when you receive this long string you can use the split method to get an array of strings

String[] answers = input.slpit(SPACER);
于 2012-05-10T11:44:13.437 回答