-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClient.java
More file actions
53 lines (43 loc) · 1.59 KB
/
ChatClient.java
File metadata and controls
53 lines (43 loc) · 1.59 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
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Użycie: java ChatClient <adres_IP_serwera> <numer_portu>");
System.exit(1);
}
String serverAddress = args[0];
int port = Integer.parseInt(args[1]);
try {
Socket socket = new Socket(serverAddress, port);
System.out.println("Połączono z serwerem.");
Scanner serverIn = new Scanner(socket.getInputStream());
PrintWriter serverOut = new PrintWriter(socket.getOutputStream(), true);
Scanner userInput = new Scanner(System.in);
System.out.print("Podaj swoje imię: ");
String clientName = userInput.nextLine();
serverOut.println(clientName);
Thread readThread = new Thread(() -> {
while (true) {
if (serverIn.hasNext()) {
String message = serverIn.nextLine();
System.out.println(message);
}
}
});
readThread.start();
while (true) {
String userMessage = userInput.nextLine();
serverOut.println(userMessage);
if ("exit".equalsIgnoreCase(userMessage)) {
break;
}
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}