-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
86 lines (64 loc) · 1.73 KB
/
Client.java
File metadata and controls
86 lines (64 loc) · 1.73 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
83
84
85
86
package chat_app;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private String username, ip;
private int port;
public Client(String username, String ip, int port) {
this.username = username;
this.ip = ip;
this.port = port;
}
public void start() {
try {
Socket socket = new Socket(ip,port);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter toServer = new PrintWriter(socket.getOutputStream(), true);
toServer.println(username);
Thread sender = new Thread(()->{
try {
Scanner s = new Scanner(System.in);
while(true) {
String message = s.nextLine();
toServer.println(message);
if(message.equalsIgnoreCase("quit")) {
socket.close();
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
});
sender.start();
Thread receive = new Thread(()->{
try {
String message;
while((message = fromServer.readLine()) != null) {
System.out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
});
receive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your username ");
String username = sc.nextLine();
System.out.print("Enter server IP ");
String ip = sc.nextLine();
System.out.print("Enter server Port ");
int port = sc.nextInt();
Client client = new Client(username,ip,port);
client.start();
}
}