Reputation: 3057
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();
Upvotes: 1
Views: 408
Reputation: 3572
This is the typical way to implement a producer-comsumer pattern: the producer will put()
a string in the queue, the server/consumer will take()
a string from the queue. If the queue is empty the server will block and wait, optionally with a timeout.
You probably don't need to bound the queue, so you could instantiate a LinkedBlockingQueue with its empty constructor.
All implementations of BlockingQueue
are thread-safe, so you don't need additional synchronisation for their basic operations.1
Upvotes: 1