-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnewClient.java
More file actions
50 lines (43 loc) · 1.71 KB
/
Copy pathnewClient.java
File metadata and controls
50 lines (43 loc) · 1.71 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
import java.io.*;
import java.net.*;
/**
* 20 questions client to connect to the game server on a specified port
*/
public class newClient {
/**.
* Connects to a local server at the specified port and handles message exchange.
*
* @param args Command line argument, specifying port number
*/
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java Client <port>");
return;
}
try {
int port = Integer.parseInt(args[0]);
// Connect to the server at localhost and specified port
Socket socket = new Socket("127.0.0.1", port);
// Reader for server messages
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Writer to send messages to the server
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Reader for user input from the console
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
String serverMessage;
while ((serverMessage = in.readLine()) != null) {
// Prints server message
System.out.println(serverMessage);
// If the server is prompting for a response, read from user and send it
if (serverMessage.endsWith(":") || serverMessage.endsWith("!")) {
String response = userInput.readLine();
out.println(response);
}
}
// Close the socket when done
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}