forked from jsjtzyy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
53 lines (49 loc) · 1.57 KB
/
Client.java
File metadata and controls
53 lines (49 loc) · 1.57 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
/* Example of Java Socket Programming (Client)
*/
package Communication;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1", 8888);
Scanner scanner = new Scanner(System.in);
//构建IO
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
BufferedReader br = new BufferedReader(new InputStreamReader(is));
System.out.println("start client completed.");
boolean running = true;
String cmd;
while (running) {
cmd = scanner.nextLine();
if (cmd.equals("exit")) {
running = false;
System.out.println("shutting down the client and server");
bw.write(cmd + "\n");
bw.flush();
} else {
//向服务器端发送一条消息
bw.write(cmd + "\n"); // never miss the "\n" as a sign of end of line
bw.flush();
//读取服务器返回的消息
String mess = br.readLine();
System.out.println("服务器:" + mess);
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}