-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.java
64 lines (55 loc) · 2.06 KB
/
Client.java
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
import java.io.*;
import java.net.*;
public class Client{
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java Client <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try {
// Connect socket to given host name and port number
Socket socket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
BufferedReader stdIn = // Get input stream from standard in (keyboard input from console)
new BufferedReader(
new InputStreamReader(System.in)) ;
String userInput;
String serverInput;
// Initialize a thread to listen for input from server
ServerListener serverListener = new ServerListener(socket);
serverListener.start();
while ((userInput = stdIn.readLine()) != null) { // Wait for input from standard in
out.println(userInput);
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
class ServerListener extends Thread {
Socket socket;
ServerListener(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedReader in =
new BufferedReader(
new InputStreamReader(socket.getInputStream())); // Input stream from server
String serverInput;
while((serverInput = in.readLine()) != null) {
System.out.println(serverInput); // Print input from server into console
}
}catch(IOException ie) {
}
}
}