Coverage Summary for Class: SocketListener (it.polimi.ingsw.Server)
| Class | Class, % | Method, % | Branch, % | Line, % |
|---|---|---|---|---|
| SocketListener | 0% (0/1) | 0% (0/3) | 0% (0/2) | 0% (0/19) |
1 package it.polimi.ingsw.Server; 2 3 import it.polimi.ingsw.Logger; 4 import it.polimi.ingsw.Network.SocketWrapper; 5 import it.polimi.ingsw.Server.Messages.Events.ClientEvent; 6 import it.polimi.ingsw.Server.Messages.Events.Internal.SocketClosedEvent; 7 import it.polimi.ingsw.Server.Messages.Events.Requests.ClientRequest; 8 import it.polimi.ingsw.Server.Messages.Message; 9 10 import java.io.IOException; 11 import java.util.concurrent.BlockingQueue; 12 13 /** 14 * Given a {@link SocketWrapper} and a {@link BlockingQueue<ClientEvent>}, moves only the {@link it.polimi.ingsw.Server.Messages.Events.ClientEvent} 15 * received on the socket to the queue. 16 */ 17 public class SocketListener implements Runnable { 18 private final SocketWrapper socket; 19 private final BlockingQueue<ClientEvent> queue; 20 21 /** 22 * Construct the listener 23 * 24 * @param socket the {@link SocketWrapper} to poll messages from 25 * @param queue the {@link BlockingQueue<ClientEvent>} to push events to 26 */ 27 private SocketListener(SocketWrapper socket, BlockingQueue<ClientEvent> queue) { 28 this.socket = socket; 29 this.queue = queue; 30 } 31 32 /** 33 * Given a socket and a queue, generate a listener and put it to work 34 * 35 * @param socket the {@link SocketWrapper} to poll messages from 36 * @param queue the {@link BlockingQueue<ClientEvent>} to push events to 37 */ 38 public static void subscribe(SocketWrapper socket, BlockingQueue<ClientEvent> queue) { 39 SocketListener sl = new SocketListener(socket, queue); 40 new Thread(sl).start(); 41 } 42 43 /** 44 * Listens on the {@link SocketWrapper} for messages, passes {@link Message}s implementing {@link ClientEvent} to the 45 * {@link BlockingQueue<ClientEvent>} for the server to read from. <br> 46 * Note: in case of read errors from the socket, the socket will be closed and the listener terminated. 47 */ 48 public void run() { 49 try { 50 while (true) { 51 Message message = socket.awaitMessage(); 52 if (message instanceof ClientRequest request) { 53 queue.put(request); 54 } else { 55 Logger.severe( 56 "Received unhandled Message that was not of type" + ClientRequest.class.getName() + ".\n"); 57 return; 58 } 59 } 60 } catch (IOException | InterruptedException e) { 61 Logger.info("closing SocketListener"); 62 try { 63 this.socket.close(); 64 queue.put(new SocketClosedEvent()); 65 } catch (Exception ee) { 66 throw new RuntimeException(ee); 67 } 68 Logger.info("closed SocketListener"); 69 } 70 } 71 }