-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientTester.java
More file actions
71 lines (58 loc) · 1.98 KB
/
ClientTester.java
File metadata and controls
71 lines (58 loc) · 1.98 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
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class ClientTester extends Thread {
public static final int PORT = 8080;
public static void main(String[] args) throws IOException {
InetAddress address = InetAddress.getByName("localhost");
Socket socket = new Socket(address, PORT);
ContentReceiver contentReceiver = new ContentReceiver(socket);
Thread listener = new Thread(contentReceiver);
listener.start();
Scanner sc = new Scanner(System.in);
String message = "";
while (true) {
System.out.println("type your message. to finish, type END");
message = sc.next();
contentReceiver.sendMessage(message);
if (message.equals("END")) {
break;
}
}
sc.close();
}
}
class ContentReceiver implements Runnable {
Socket socket;
BufferedReader in;
PrintWriter out;
public ContentReceiver(Socket socket) throws IOException {
this.socket = socket;
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
}
public void sendMessage(String message) {
this.out.println(message);
}
@Override
public void run() {
try {
while(true) {
String newText = in.readLine();
if (newText.equals("END")) break;
System.out.println("new message from server: " + newText);
}
} catch(Exception e) {
System.out.println("an error occurred.");
e.printStackTrace();
} finally {
System.out.println("closing connection " + socket);
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}