-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClient.java
More file actions
72 lines (57 loc) · 1.94 KB
/
Copy pathChatClient.java
File metadata and controls
72 lines (57 loc) · 1.94 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
70
71
72
package Chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
/**
* @author wukai
* @date 2019/6/14
*/
public class ChatClient {
public static void main(String[] args) throws IOException, InterruptedException {
String serverIp = "127.0.0.1";
int serverPort = 8888;
Socket socket = new Socket(serverIp, serverPort);
final OutputStream outputStream = socket.getOutputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//读取控制台输入
final Scanner scanner = new Scanner(System.in);
final CountDownLatch countDownLatch = new CountDownLatch(2);
//处理socket读请求
new Thread(new Runnable() {
public void run() {
try {
String msg = null;
while ((msg = reader.readLine()) != null) {
System.out.println(msg);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
countDownLatch.countDown();
}
}
}).start();
//处理从控制写数据到socket
new Thread(new Runnable() {
public void run() {
try {
String msg = null;
while ((msg = scanner.next()) != null) {
msg += "\n";
outputStream.write(msg.getBytes());
}
} catch (Exception e) {
e.printStackTrace();
}finally {
countDownLatch.countDown();
}
}
}).start();
countDownLatch.await();
socket.close();
}
}