Browse Source

merge issues fix

remotes/origin/client-handler
Valentin Spiroski 11 months ago
parent
commit
12e96a7361
  1. 2
      .gitignore
  2. 65
      src/main/java/ClientHandler.java
  3. 29
      src/main/java/Server.java

2
.gitignore

@ -1,2 +0,0 @@
/target/
/src/main/java/ChatServer

65
src/main/java/ClientHandler.java

@ -1,65 +0,0 @@
import java.io.*;
import java.net.Socket;
public class ClientHandler implements Runnable {
private ChatServer chatServer;
private Socket connectionToClient;
private String name;
private BufferedReader fromClientReader;
private PrintWriter toClientWriter;
// Constructor for ClientHandler
public ClientHandler(ChatServer chatServer, Socket connectionToClient) {
this.chatServer = chatServer;
this.connectionToClient = connectionToClient;
name = connectionToClient.getInetAddress().getHostAddress(); // Use the client's IP address as their name for simplicity
new Thread(this).start();} // Start a new thread for this client handler
@Override
public void run() {
try {
// Set up input and output streams for communication with the client
fromClientReader = new BufferedReader (new InputStreamReader(connectionToClient.getInputStream()));
toClientWriter = new PrintWriter (new OutputStreamWriter(connectionToClient.getOutputStream()));
chatServer.broadcastMessage(name + " connected."); // Broadcast a message when the client is connected
// Read messages from the client and broadcast them to all clients
String message = fromClientReader.readLine();
while (message!=null) {
// Broadcast the client's message to all connected clients
chatServer.broadcastMessage(name + ": " + message);
message = fromClientReader.readLine();
}
}
catch (IOException e) {
throw new RuntimeException(e); // Handle exceptions by throwing a runtime exception
}
finally {
//chatServer.removeClient(this);
chatServer.broadcastMessage(name + " disconnected."); // Broadcast a message when the client is disconnected
// Close resources in the finally block
if (fromClientReader != null) {
try {
fromClientReader.close();
}
catch (IOException e){
e.printStackTrace();
}
}
if (toClientWriter != null) {
toClientWriter.close();
}
}
}
//Method to send a message to the client
public void sendMessage(String message) {
toClientWriter.println(message); // Send the message to the client
toClientWriter.flush(); // Flush the stream
}
}

29
src/main/java/Server.java

@ -1,29 +0,0 @@
package server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket serverSocket;
public void ChatServer(int port) {
try {
serverSocket = new ServerSocket(port);
System.out.println("Started ChatServer on port " + port);
Socket connectionToClient = serverSocket.accept();
System.out.println("Accepted new Client");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Loading…
Cancel
Save