Hello all I am writing server socket inside my Android app. It should allow only one client. Interesting thing is that I want my server to send messages(strings) to client while they are available. I have queue of strings from which i want my server try taking strings on by one and send to the client, if queue empty do not send and as long as some string is pushed into queue send it. Here is how I do that:
public class Resource {
public static Queue<String> q = new LinkedList<String>();
public static synchronized void addString(String commands) {//for reader
semaphore.add(commands);
}
public synchronized String getString() {
if (!semaphore.isEmpty()) {
return semaphore.remove();
} else return "0";
}
}
For that I have a queue q of string where I can add strings from another class. Here is my server code:
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
// Listens for a connection to be made to this socket.
Socket socket = my_serverSocket.accept();
//send message to client
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("1");
BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
String msg = in.readLine();
System.out.println("message is: " + msg);
// tidy up
//in.close();
//socket.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SecurityException se) {
se.printStackTrace();
}
}
}
}).start();