我有一个在 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。我怎么能那样做?