forked from AdvancedProgramming1404/HW-10-Socket-Programming
Compare commits
4
Commits
240eac0504
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74f963ff8e | ||
|
|
87a5ca499d | ||
|
|
4489f62a11 | ||
|
|
d965c694fa |
@@ -1,18 +1,27 @@
|
|||||||
package com.university.chat.Client;
|
package com.university.chat.Client;
|
||||||
|
|
||||||
|
import com.university.chat.Common.ChatMessage;
|
||||||
|
import com.university.chat.Common.FileMessage;
|
||||||
|
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
|
||||||
public class ServerListener implements Runnable{
|
public class ServerListener implements Runnable{
|
||||||
// TODO: store the ObjectInputStream from the user socket
|
private final ObjectInputStream in;
|
||||||
// (this should be the same input stream the
|
|
||||||
// chatClient created when connecting)
|
public ServerListener(ObjectInputStream in) {
|
||||||
|
this.in = in;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
// TODO: In an infinite loop read objects from the server
|
while(true){
|
||||||
// - if it's a ChatMessage -> print "<sender>: <content>"
|
Object recived = in.readObject();
|
||||||
// - if it's a FileMessage -> print that a file was received
|
if(recived instanceof ChatMessage msg)
|
||||||
// (filename + sender), it's already
|
System.out.println(msg.getSender() + "==> " + msg.getContent());
|
||||||
// saved to disk by the server.
|
else if(recived instanceof FileMessage fileMsg)
|
||||||
|
System.out.println(fileMsg.getSender() + "sent ==> " +fileMsg.getFilename());
|
||||||
|
}
|
||||||
} catch (Exception e){
|
} catch (Exception e){
|
||||||
System.out.println("Disconnected from server");
|
System.out.println("Disconnected from server");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,108 @@
|
|||||||
package com.university.chat.Client;
|
package com.university.chat.Client;
|
||||||
|
|
||||||
public class chatClient {
|
import com.university.chat.Common.ChatMessage;
|
||||||
public static void main() {
|
import com.university.chat.Common.FileMessage;
|
||||||
// TODO: Connecting to the server
|
import com.university.chat.Common.MessageType;
|
||||||
// 1. Create a socket and connect to the server
|
|
||||||
// 2. Create an ObjectOutputStream (out) and ObjectInputStream (in)
|
|
||||||
// from the socket's streams — output FIRST, then input.
|
|
||||||
// 2. Get the username, and send a LOGIN ChatMessage with that username
|
|
||||||
// 3. Start a new Thread running a ServerListener(in) so incoming
|
|
||||||
// messages are handled concurrently.
|
|
||||||
|
|
||||||
while (true){
|
import java.io.IOException;
|
||||||
try {
|
import java.io.ObjectInputStream;
|
||||||
// TODO: Program loop — read a line from the console and act on it:
|
import java.io.ObjectOutputStream;
|
||||||
// - "/msg <user> <text>" -> build & send a PRIVATE_MESSAGE
|
import java.net.Socket;
|
||||||
// - "/users" -> build & send a USER_LIST request
|
import java.nio.file.Files;
|
||||||
// - "/sendfile <user> <path>" -> read the file into a byte[]
|
import java.nio.file.Path;
|
||||||
// (you can use TransferProgress
|
import java.nio.file.Paths;
|
||||||
// to show progress)
|
import java.util.Scanner;
|
||||||
// and send it as a FileMessage
|
|
||||||
// - anything else -> send a PUBLIC_MESSAGE
|
public class chatClient {
|
||||||
// Remember to flush() the output stream after writeObject().
|
|
||||||
} catch (Exception e){
|
public static void main() {
|
||||||
System.out.println("command failed: " + e.getMessage());
|
|
||||||
|
final String SERVER_HOST = "localhost";
|
||||||
|
final int SERVER_PORT = 600;
|
||||||
|
|
||||||
|
Scanner input = new Scanner(System.in);
|
||||||
|
|
||||||
|
try {
|
||||||
|
Socket clientSocket = new Socket(SERVER_HOST, SERVER_PORT);
|
||||||
|
|
||||||
|
ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream());
|
||||||
|
output.flush();
|
||||||
|
ObjectInputStream inputStream = new ObjectInputStream(clientSocket.getInputStream());
|
||||||
|
|
||||||
|
System.out.print("Username: ");
|
||||||
|
String username = input.nextLine();
|
||||||
|
|
||||||
|
output.writeObject(new ChatMessage(MessageType.LOGIN, username, null, null));
|
||||||
|
output.flush();
|
||||||
|
|
||||||
|
Thread serverThread = new Thread(new ServerListener(inputStream));
|
||||||
|
serverThread.start();
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
try {
|
||||||
|
String command = input.nextLine();
|
||||||
|
|
||||||
|
if (command.startsWith("/msg ")) {
|
||||||
|
String[] args = command.substring(5).split(" ", 2);
|
||||||
|
|
||||||
|
String recipient = args[0];
|
||||||
|
String message = args.length > 1 ? args[1] : "";
|
||||||
|
|
||||||
|
output.writeObject(new ChatMessage(
|
||||||
|
MessageType.PRIVATE_MESSAGE,
|
||||||
|
username,
|
||||||
|
recipient,
|
||||||
|
message));
|
||||||
|
|
||||||
|
output.flush();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (command.equals("/users")) {
|
||||||
|
output.writeObject(new ChatMessage(
|
||||||
|
MessageType.USER_LIST,
|
||||||
|
username,
|
||||||
|
null,
|
||||||
|
null));
|
||||||
|
|
||||||
|
output.flush();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (command.startsWith("/sendfile ")) {
|
||||||
|
String[] args = command.substring(10).split(" ", 2);
|
||||||
|
|
||||||
|
String recipient = args[0];
|
||||||
|
Path file = Paths.get(args[1]);
|
||||||
|
|
||||||
|
byte[] fileData = Files.readAllBytes(file);
|
||||||
|
String fileName = file.getFileName().toString();
|
||||||
|
|
||||||
|
output.writeObject(new FileMessage(
|
||||||
|
username,
|
||||||
|
recipient,
|
||||||
|
fileName,
|
||||||
|
fileData));
|
||||||
|
|
||||||
|
output.flush();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
output.writeObject(new ChatMessage(
|
||||||
|
MessageType.PUBLIC_MESSAGE,
|
||||||
|
username,
|
||||||
|
null,
|
||||||
|
command));
|
||||||
|
|
||||||
|
output.flush();
|
||||||
|
|
||||||
|
} catch (Exception ex) {
|
||||||
|
System.out.println("Command failed: " + ex.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} catch (IOException ex) {
|
||||||
|
System.out.println(ex.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,28 @@
|
|||||||
package com.university.chat.Server;
|
package com.university.chat.Server;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
import java.net.Socket;
|
||||||
|
|
||||||
public class ChatServer {
|
public class ChatServer {
|
||||||
// TODO: declare a single shared UserManager instance (static final)
|
public static final UserManager userManager = new UserManager();
|
||||||
// This MUST be shared by all ClientSession threads so that
|
public static ServerSocket serverSocket;
|
||||||
// broadcasting and private messaging work correctly.
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
// TODO: Create a ServerSocket
|
try {
|
||||||
|
serverSocket = new ServerSocket(600);
|
||||||
// TODO: In an infinite loop:
|
} catch (IOException e){
|
||||||
// accept an incoming client connection
|
throw new RuntimeException(e);
|
||||||
// make a new thread running ClientSession for each user.
|
}
|
||||||
|
while(true){
|
||||||
|
try {
|
||||||
|
Socket socket = serverSocket.accept();
|
||||||
|
System.out.println("New user connected.");
|
||||||
|
ClientSession session = new ClientSession(socket, userManager);
|
||||||
|
new Thread(session).start();
|
||||||
|
} catch(IOException e){
|
||||||
|
System.err.println("Cannot connect: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,44 +2,80 @@ package com.university.chat.Server;
|
|||||||
|
|
||||||
import com.university.chat.Common.ChatMessage;
|
import com.university.chat.Common.ChatMessage;
|
||||||
import com.university.chat.Common.FileMessage;
|
import com.university.chat.Common.FileMessage;
|
||||||
|
import com.university.chat.Common.MessageType;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.io.ObjectOutputStream;
|
||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
|
|
||||||
public class ClientSession implements Runnable {
|
public class ClientSession implements Runnable {
|
||||||
|
|
||||||
private String username;
|
private String username;
|
||||||
|
private final UserManager userManager;
|
||||||
|
private final Socket socket;
|
||||||
|
private ObjectOutputStream out;
|
||||||
|
private ObjectInputStream in;
|
||||||
|
|
||||||
public ClientSession(Socket socket, UserManager userManager) {
|
public ClientSession(Socket socket, UserManager userManager) {
|
||||||
// TODO : Create an ObjectOutputStream from socket.getOutputStream()
|
this.socket = socket;
|
||||||
// and an ObjectInputStream from socket.getInputStream().
|
this.userManager = userManager;
|
||||||
|
try {
|
||||||
|
out = new ObjectOutputStream(socket.getOutputStream());
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println(e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
in = new ObjectInputStream(socket.getInputStream());
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println(e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
|
System.out.println("Welcome");
|
||||||
|
boolean isLogedIn = false;
|
||||||
|
Object firstObject = in.readObject();
|
||||||
|
if(firstObject instanceof ChatMessage){
|
||||||
|
isLogedIn = ((ChatMessage)firstObject).getType() == MessageType.LOGIN;
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: Welcome the user (login step)
|
if(!isLogedIn){
|
||||||
// 1. Read the first object sent by the client.
|
socket.close();
|
||||||
// 2. Check it's a ChatMessage with type LOGIN.
|
return;
|
||||||
// 3. Extract the username.
|
}
|
||||||
// 4. Try to register the user via userManager.addUser(...).
|
|
||||||
// 5. If the username is taken, send back LOGIN_FAILED and close the socket.
|
|
||||||
// 6. Otherwise, create the user's folders with FileManager.createUserFolders(...)
|
|
||||||
// and send back LOGIN_SUCCESS.
|
|
||||||
|
|
||||||
// TODO: Main message loop
|
username = ((ChatMessage) firstObject).getSender();
|
||||||
// In a loop, call in.readObject(), you can separate messages by their type:
|
if(userManager.addUser(username, this)){
|
||||||
// - if it's a ChatMessage -> call handleChatMessage(msg)
|
System.out.println(username + " user name added.");
|
||||||
// - if it's a FileMessage -> call handleFileMessage(fileMsg)
|
FileManager.createUserFolders(username);
|
||||||
// Keep looping until the connection is closed (an exception will be thrown).
|
out.writeObject(MessageType.LOGIN_SUCCESS);
|
||||||
|
out.flush();
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
System.out.println("try another username.");
|
||||||
|
out.writeObject(MessageType.LOGIN_FAILED);
|
||||||
|
out.flush();
|
||||||
|
socket.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while(true){
|
||||||
|
Object obj = in.readObject();
|
||||||
|
if(obj instanceof ChatMessage)
|
||||||
|
handleChatMessage((ChatMessage) obj);
|
||||||
|
else if(obj instanceof FileMessage)
|
||||||
|
handleFileMessage((FileMessage) obj);
|
||||||
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.out.println("Disconnected: " + username);
|
System.out.println("Disconnected: " + username);
|
||||||
} finally {
|
} finally {
|
||||||
// TODO: Remove the user from UserManager so they no longer
|
userManager.removeUser(username);
|
||||||
// receive broadcasts or appear in users list
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,13 +83,32 @@ public class ClientSession implements Runnable {
|
|||||||
private void handleChatMessage(ChatMessage msg) throws IOException {
|
private void handleChatMessage(ChatMessage msg) throws IOException {
|
||||||
switch (msg.getType()) {
|
switch (msg.getType()) {
|
||||||
case PUBLIC_MESSAGE -> {
|
case PUBLIC_MESSAGE -> {
|
||||||
// TODO: Broadcast this message to every connected client.
|
Iterable<ClientSession> users = userManager.getAllSessions();
|
||||||
|
for(ClientSession user : users){
|
||||||
|
user.send(msg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case PRIVATE_MESSAGE -> {
|
case PRIVATE_MESSAGE -> {
|
||||||
// TODO: Forward this message to the receiver user.
|
ClientSession receiver = userManager.getUser(msg.getReceiver());
|
||||||
|
if(receiver != null){
|
||||||
|
receiver.send(msg);
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
send(new ChatMessage(
|
||||||
|
MessageType.PRIVATE_MESSAGE,
|
||||||
|
"server",
|
||||||
|
username,
|
||||||
|
"User doesn't exist: " + msg.getReceiver()
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case USER_LIST -> {
|
case USER_LIST -> {
|
||||||
// TODO: Reply to the requester with the list of online users.
|
send(new ChatMessage(
|
||||||
|
MessageType.USER_LIST,
|
||||||
|
"server",
|
||||||
|
username,
|
||||||
|
userManager.listUsers()
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -66,6 +121,11 @@ public class ClientSession implements Runnable {
|
|||||||
Files.write(sentPath, fileMsg.getData());
|
Files.write(sentPath, fileMsg.getData());
|
||||||
Files.write(recvPath, fileMsg.getData());
|
Files.write(recvPath, fileMsg.getData());
|
||||||
|
|
||||||
// TODO: Forward the received file-message to the destination user.
|
ClientSession receiver = userManager.getUser(fileMsg.getReceiver());
|
||||||
|
receiver.send(fileMsg);
|
||||||
|
}
|
||||||
|
private synchronized void send(Object obj) throws IOException{
|
||||||
|
out.writeObject(obj);
|
||||||
|
out.flush();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user