Repository navigation
Expand file tree
/
Copy pathEchoClient.java
More file actions
69 lines (57 loc) · 1.99 KB
/
Copy pathEchoClient.java
File metadata and controls
69 lines (57 loc) · 1.99 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
package echo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;
public class EchoClient {
private static final String SERVER_IP = "192.168.0.182";
public static void main(String[] args) {
Socket socket = null;
Scanner scanner = null;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(SERVER_IP, EchoServer.PORT));
log("connected");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"), true);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
scanner = new Scanner(System.in);
while(true) {
System.out.print(">");
String line = scanner.nextLine();
if("exit".equals(line)) {
break;
}
pw.println(line);
String data = br.readLine();
if(data == null) {
log("closed by server");
break;
}
System.out.println("<" + data);
}
} catch (SocketException e) {
System.out.println("[client] suddenly closed by server");
} catch (IOException e) {
System.out.println("[client] error:" + e);
} finally {
try {
if(socket != null && !socket.isClosed()) {
socket.close();
}
if(scanner != null) {
scanner.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void log(String message) {
System.out.println("[EchoClient] " + message);
}
}