This repository was archived by the owner on Nov 10, 2020. It is now read-only.
forked from husseinalosman/simpleChat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerConsole.java
More file actions
119 lines (99 loc) · 2.76 KB
/
ServerConsole.java
File metadata and controls
119 lines (99 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import common.ChatIF;
import server.EchoServer;
import java.io.IOException;
import java.util.Scanner;
/**
* ServerConsole.java - The CLI of a chat server
*
* @author Xiaoxuan Wang 300133594
*/
public class ServerConsole implements ChatIF
{
// Class variables *************************************************
/**
* The default port to listen on.
*/
final public static int DEFAULT_PORT = 5555;
// Instance variables **********************************************
/**
* The instance of the server.
*/
EchoServer server;
/**
* Scanner to read from the console
*/
Scanner fromConsole;
// Constructors ****************************************************
/**
* Constructs an instance of the ServerConsole UI.
*
* @param port The port to listen on.
*/
public ServerConsole(int port)
{
server = new EchoServer(port, this);
try
{
server.listen();
}
catch (IOException e)
{
System.err.println("[E] Could not listen for clients!");
e.printStackTrace();
}
// Create scanner object to read from console
fromConsole = new Scanner(System.in);
}
// Instance methods ************************************************
/**
* This method is responsible for the creation of the Client UI.
*
* @param args [0] The host to connect to.
*/
public static void main(String[] args)
{
int port; // Port to listen on
try
{
port = Integer.parseInt(args[0]); //Get port from command line
}
catch (ArrayIndexOutOfBoundsException | NumberFormatException e)
{
port = DEFAULT_PORT; //Set port to 5555
}
ServerConsole serverConsole = new ServerConsole(port);
serverConsole.accept();
}
/**
* This method waits for input from the console. Once it is
* received, it sends it to the server's message handler.
*/
public void accept()
{
try
{
String message;
while (true)
{
message = fromConsole.nextLine();
server.handleMessageFromServerUI(message);
}
}
catch (Exception e)
{
System.err.println("[E] Unexpected error while reading from console!");
}
}
// Class methods ***************************************************
/**
* This method overrides the method in the ChatIF interface. It
* displays a message onto the screen.
*
* @param message The string to be displayed.
*/
public void display(String message)
{
System.out.println(message);
}
}
// End of ConsoleChat class