Reputation: 1655
On Servlet side:
for (GameParticipant activePlayer : connector.activePlayers) {
activePlayer.out.println(response);
activePlayer.out.flush();
System.out.println("Server sending board state to all game participants:" + response);
(activePlayer.out is a PrintWriter saved in the server from the HttpResponse object obtained when that client connected the first time)
On clinet side:
private void receiveMessageFromServer() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String input = null;
while ((input = br.readLine()) != null){
sb.append(input).append(" ");
}
}
For some reason, this communication works only the first time, when the client requests connection and waits for response in the same method, while the server uses the PrintWriter obtained directly fron the available HttpRespnse in the doPost method. After that, when the servlet tries to reuse the PrintWriter to talk to the clinet outside of a doPost method, nothing happens, the message never gets to the client. Any ideas?
P.S. In client constructor:
try {
url = new URL("http://localhost:8182/stream");
conn = (HttpURLConnection) url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException ioE) {
ioE.printStackTrace();
}
Upvotes: 0
Views: 880
Reputation: 311039
The response output stream isn't valid outside the doPost() method, or more properly speaking the service() method. It can only be used to send one response. However PrintWriter swallows exceptions, as you will find when you check its error status, so you didn't see the problem.
In other words your entire server-side design is flawed. You can't misuse the Servlet Specification in that way.
Upvotes: 1