I have a socket server running on an android device. Then from a client I send to the server a string and the server returns the same(echo server). The thing that I am trying to do is to get some other strings too, not only the one that I send it. Here is the server code:
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);
Here is the client code:
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;
}
I want to return answer1,answer2,asnwer3,answer4 also. How i could do that?
You are dealing with Strins, so i’d suggest to use readUTF() and writeUTF().
The point is that you can send only one string at time. If you want to send more strings you have to create a single String and putting a sort of spacer between the strings.
When i wrote somthing similar i used the newline character as the spacer and formatted my string in the following way:
String1 + SPACER + String2 + SPACER + String….
On the other side when you receive this long string you can use the split method to get an array of strings