COMP2396
Loading...
Searching...
No Matches
Controller.java
Go to the documentation of this file.
1import java.awt.event.ActionEvent;
2import java.awt.event.ActionListener;
3import java.io.IOException;
4import java.io.PrintWriter;
5import java.net.Socket;
6import java.net.UnknownHostException;
7import java.util.Scanner;
8
9public class Controller {
10
11 private View view;
12 private ActionListener upButtonListener;
13 private ActionListener downButtonListener;
14
15 private Socket socket;
16 private Scanner in;
17 private PrintWriter out;
18
20 this.view = view;
21 }
22
23 public void start() {
24 try {
25 this.socket = new Socket("127.0.0.1", 58901);
26 this.in = new Scanner(socket.getInputStream());
27 this.out = new PrintWriter(socket.getOutputStream(), true);
28 } catch (UnknownHostException e) {
29 e.printStackTrace();
30 } catch (IOException e) {
31 e.printStackTrace();
32 }
33
34 upButtonListener = new ActionListener() {
35 public void actionPerformed(ActionEvent actionEvent) {
36 out.println("UP");
37 System.out.println("Client Sent: UP");
38 }
39 };
40 view.getUpButton().addActionListener(upButtonListener);
41
42 downButtonListener = new ActionListener() {
43 public void actionPerformed(ActionEvent actionEvent) {
44 out.println("DOWN");
45 System.out.println("Client Sent: DOWN");
46 }
47 };
48 view.getDownButton().addActionListener(downButtonListener);
49
50 // Creates a new Thread for reading server messages
51 Thread handler = new ClinetHandler(socket);
52 handler.start();
53 }
54
55 class ClinetHandler extends Thread {
56 private Socket socket;
57
58 public ClinetHandler(Socket socket) {
59 this.socket = socket;
60 }
61
62 @Override
63 public void run() {
64 try {
65 readFromServer();
66 } catch (Exception e) {
67 e.printStackTrace();
68 }
69 }
70
71 public void readFromServer() throws Exception {
72 try {
73 while (in.hasNextLine()) {
74 var command = in.nextLine();
75 System.out.println("Client Received: " + command);
76 out.flush();
77 view.getResultLabel().setText(command.trim());
78 }
79 } catch (Exception e) {
80 e.printStackTrace();
81 } finally {
82 socket.close();
83 }
84 }
85 }
86
87}
PrintWriter out
ActionListener downButtonListener
Scanner in
Controller(View view)
ActionListener upButtonListener
void start()
Socket socket
Definition View.java:18
JButton getDownButton()
Definition View.java:80
JLabel getResultLabel()
Definition View.java:84
JButton getUpButton()
Definition View.java:76