135 lines
3.9 KiB
Java
135 lines
3.9 KiB
Java
package com.university.chat.Client;
|
|
|
|
import com.university.chat.Common.ChatMessage;
|
|
import com.university.chat.Common.FileMessage;
|
|
import com.university.chat.Common.MessageType;
|
|
|
|
import java.io.File;
|
|
import java.io.ObjectInputStream;
|
|
import java.io.ObjectOutputStream;
|
|
import java.net.Socket;
|
|
import java.nio.file.Files;
|
|
import java.util.Scanner;
|
|
|
|
public class chatClient {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
try {
|
|
Socket socket = new Socket("localhost", 8080);
|
|
|
|
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
|
|
|
|
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
|
|
|
|
Scanner scanner = new Scanner(System.in);
|
|
|
|
System.out.print("Enter username: ");
|
|
String username = scanner.nextLine();
|
|
|
|
ChatMessage login = new ChatMessage(
|
|
MessageType.LOGIN,
|
|
username,
|
|
"",
|
|
""
|
|
);
|
|
|
|
out.writeObject(login);
|
|
|
|
new Thread(new ServerListener(in)).start();
|
|
|
|
while (true) {
|
|
|
|
try {
|
|
|
|
String text = scanner.nextLine();
|
|
|
|
if (text.startsWith("/msg ")) {
|
|
|
|
String[] parts = text.split(" ", 3);
|
|
|
|
if (parts.length < 3) {
|
|
System.out.println("Wrong command.");
|
|
continue;
|
|
}
|
|
|
|
ChatMessage message = new ChatMessage(
|
|
MessageType.PRIVATE_MESSAGE,
|
|
username,
|
|
parts[1],
|
|
parts[2]
|
|
);
|
|
|
|
out.writeObject(message);
|
|
out.flush();
|
|
}
|
|
|
|
else if (text.equals("/users")) {
|
|
|
|
ChatMessage message = new ChatMessage(
|
|
MessageType.USER_LIST,
|
|
username,
|
|
"",
|
|
""
|
|
);
|
|
|
|
out.writeObject(message);
|
|
out.flush();
|
|
}
|
|
|
|
else if (text.startsWith("/sendfile ")) {
|
|
|
|
String[] parts = text.split(" ", 3);
|
|
|
|
if (parts.length < 3) {
|
|
System.out.println("Wrong command.");
|
|
continue;
|
|
}
|
|
|
|
File file = new File(parts[2]);
|
|
|
|
if (!file.exists()) {
|
|
System.out.println("File not found.");
|
|
continue;
|
|
}
|
|
|
|
byte[] data = Files.readAllBytes(file.toPath());
|
|
|
|
FileMessage fileMessage = new FileMessage(
|
|
username,
|
|
parts[1],
|
|
file.getName(),
|
|
data
|
|
);
|
|
|
|
out.writeObject(fileMessage);
|
|
out.flush();
|
|
|
|
System.out.println("File sent.");
|
|
}
|
|
|
|
else {
|
|
|
|
ChatMessage message = new ChatMessage(
|
|
MessageType.PUBLIC_MESSAGE,
|
|
username,
|
|
"",
|
|
text
|
|
);
|
|
|
|
out.writeObject(message);
|
|
out.flush();
|
|
}
|
|
|
|
} catch (Exception e) {
|
|
System.out.println("Command failed.");
|
|
}
|
|
|
|
}
|
|
|
|
} catch (Exception e) {
|
|
}
|
|
|
|
}
|
|
|
|
} |