-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMC_Client.java
More file actions
93 lines (78 loc) · 2.64 KB
/
MC_Client.java
File metadata and controls
93 lines (78 loc) · 2.64 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
87
88
89
90
91
92
93
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class MC_Client {
private static final String server_host = "localhost";
private static final int server_port = 22554;
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public void start() {
try {
socket = new Socket(server_host, server_port);
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
System.out.println("> Connected to the server.");
Thread receiveThread = new Thread(this::receiveMessages);
receiveThread.start();
sendUsername();
sendMessageLoop();
} catch (IOException e) {
System.out.println("> Error: Failed to connect to the server.");
} finally {
closeConnection();
}
}
private void sendUsername() throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.print("> Please enter your username: ");
String username = scanner.nextLine();
outputStream.write(username.getBytes());
}
private void sendMessageLoop() throws IOException {
Scanner scanner = new Scanner(System.in);
String message;
while (true) {
message = scanner.nextLine();
outputStream.write(message.getBytes());
if (message.equalsIgnoreCase("exit")) {
break;
}
}
}
private void receiveMessages() {
byte[] buffer = new byte[1024];
int bytesRead;
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
String message = new String(buffer, 0, bytesRead).trim();
System.out.println("> "+message);
}
} catch (IOException e) {
System.out.println("> Disconnected from the server.");
} finally {
closeConnection();
}
}
private void closeConnection() {
try {
if (socket != null) {
socket.close();
}
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MC_Client client = new MC_Client();
client.start();
}
}