Coverage Summary for Class: Connection (it.polimi.ingsw.view.socket)
Class | Class, % | Method, % | Line, % |
---|---|---|---|
Connection | 0% (0/ 1) | 0% (0/ 7) | 0% (0/ 38) |
1 package it.polimi.ingsw.view.socket;
2
3 import java.io.Closeable;
4 import java.io.IOException;
5 import java.io.PrintWriter;
6 import java.net.Socket;
7 import java.util.Scanner;
8
9 import it.polimi.ingsw.utils.Observable;
10 import it.polimi.ingsw.utils.Observer;
11 import it.polimi.ingsw.utils.Pinger;
12
13 /**
14 * Client Side socket connection handler class
15 */
16 public class Connection extends Observable<String> implements Runnable, Observer<String>, Closeable {
17 /**
18 * Socket
19 */
20 private final Socket socket;
21 /**
22 * Receiver
23 */
24 private final Scanner receiver;
25 /**
26 * Sender
27 */
28 private final PrintWriter sender;
29 /**
30 * Pinger
31 */
32 private final Pinger pinger;
33 /**
34 * Socket connection
35 */
36 private boolean isActive = false;
37 /**
38 * Owner of the connection
39 */
40 private AppInterface master;
41
42 /**
43 * Connection Constructor
44 *
45 * @param ip server ip
46 * @param port server port
47 * @throws IOException
48 */
49 public Connection(String ip, int port) throws IOException {
50 this.socket = new Socket(ip, port);
51 this.receiver = new Scanner(socket.getInputStream());
52 this.sender = new PrintWriter(socket.getOutputStream());
53 socket.setSoTimeout(30000);
54 pinger = new Pinger(this);
55 }
56
57 /**
58 * Set Connection Owner
59 *
60 * @param master owner
61 */
62 public void setMaster(AppInterface master) {
63 this.master = master;
64 }
65
66 /**
67 * Send a data in the socket
68 *
69 * @param toSend data to send
70 */
71 public synchronized void send(String toSend) {
72 if (!isActive)
73 return;
74 sender.println(toSend);
75 sender.flush();
76 }
77
78 /**
79 * Get Socket connection
80 *
81 * @return socket connection
82 */
83 public boolean getStatus() {
84 return isActive;
85 }
86
87 /**
88 * close socket
89 *
90 */
91 @Override
92 public void close() {
93 isActive = false;
94 try {
95 pinger.stop();
96 sender.close();
97 receiver.close();
98 socket.close();
99 } catch (IOException e) {
100 // Fail Close
101 }
102 }
103
104 /**
105 * Function to handle push data from server, then notify to all observers of
106 * this connection
107 */
108 @Override
109 public void run() {
110
111 this.isActive = true;
112 new Thread(pinger).start();
113
114 try {
115 while (isActive) {
116 String serverPush = receiver.nextLine();
117 notify(serverPush);
118 }
119 } catch (Exception e) {
120 if (isActive)
121 master.onDisconnection();
122 close();
123 }
124 }
125
126 /**
127 * Function triggered when need send data to server
128 */
129 @Override
130 public void update(String toSend) {
131 send(toSend);
132 }
133 }