-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCPClient.java
More file actions
82 lines (74 loc) · 2.38 KB
/
TCPClient.java
File metadata and controls
82 lines (74 loc) · 2.38 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
73
74
75
76
77
78
79
80
81
82
package socket;
import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;
public class TCPClient {
Socket clientSocket = null;
BufferedReader reader = null;
private static final int PORT = 65000;
public static void main(String[] args) throws IOException {
new TCPClient();
System.exit(0);
}
public TCPClient() {
clientSocket = new Socket();
try {
clientSocket.connect(new InetSocketAddress("localhost", PORT));
new getInputStream().start();
System.out.println("Client started!");
reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String receiveStr = null;
while ((receiveStr = reader.readLine()) != null) {
//接收服务端发来的数据
if (receiveStr.equals("exit")) {
break;
}
System.out.println(receiveStr);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
if (clientSocket != null) {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class getInputStream extends Thread {
@Override
public void run() {
BufferedReader is = null;
PrintWriter os = null;
try {
is = new BufferedReader(new InputStreamReader(System.in));
os = new PrintWriter(new BufferedOutputStream(clientSocket.getOutputStream()));
String str = null;
while ((str = is.readLine()) != null) {
os.println(str);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}