-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
65 lines (56 loc) · 2.1 KB
/
Client.java
File metadata and controls
65 lines (56 loc) · 2.1 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
package org.example;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static final String SERVER_HOST = "localhost";
public static final String SERVER_PORT = "3345";
private PrintWriter out;
private BufferedReader in;
public static void main(String[] args){
try (Socket socket = new Socket("localhost", 3345)){
System.out.println("Connection to server successful");
Thread receiveThread = new Thread(new ReceiveThread(socket));
receiveThread.start();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String userInput = bufferedReader.readLine();
while(userInput != null){
out.println(userInput);
userInput = bufferedReader.readLine();
if (userInput.isEmpty()) {
break;
}
}
}
catch (UnknownHostException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public static class ReceiveThread implements Runnable{
public static String name;
public static Socket socket;
public ReceiveThread(Socket socket){
this.socket = socket;
};
@Override
public void run(){
System.out.printf("%s started... \n", Thread.currentThread().getName());
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message;
while ((message = in.readLine()) != null) {
System.out.println("Message from server: " + message);
break;
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
System.out.printf("%s fiished... \n", Thread.currentThread().getName());
}
}
}