-
Notifications
You must be signed in to change notification settings - Fork 0
/
EchoUser.java
80 lines (66 loc) · 2.54 KB
/
EchoUser.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoUser {
// The user socket
private static Socket userSocket = null;
// The output stream
private static PrintStream outToServer = null;
// The input stream
private static BufferedReader inFromServer = null;
private static BufferedReader inFromUser = null;
public static void main(String[] args) {
// The default port.
int portNumber = 8000;
// The default host.
String host = "localhost";
String sentence;
if (args.length < 2) {
System.out.println("Usage: java User <host> <portNumber>\n"
+ "Now using host=" + host + ", portNumber=" + portNumber);
} else {
host = args[0];
portNumber = Integer.valueOf(args[1]).intValue();
}
/*
* Open a socket on a given host and port. Open input and output streams.
*/
try {
// YOUR CODE
userSocket = new Socket(host,portNumber);
inFromUser = new BufferedReader(new InputStreamReader(System.in));
outToServer = new PrintStream(userSocket.getOutputStream());
inFromServer = new BufferedReader(new InputStreamReader(userSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host "
+ host);
}
/*
* If everything has been initialized then we want to send message to the
* socket we have opened a connection to on the port portNumber.
* When we receive the echo, print it out.
*/
try {
// YOUR CODE
sentence = inFromUser.readLine();
outToServer.println(sentence);
System.out.println("echo: " + inFromServer.readLine());
/*
* Close the output stream, close the input stream, close the socket.
*/
outToServer.close();
inFromServer.close();
userSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}