Add: Added Partial Logic For Client Connection Handling And Termination In TCPServer.java.
This commit is contained in:
@@ -12,37 +12,44 @@ public class ClientHandler implements Runnable {
|
||||
PrintWriter out = null;
|
||||
List<ClientHandler> clientHandlers;
|
||||
GameController gameController;
|
||||
|
||||
public ClientHandler(Socket clientSocket, List<ClientHandler> clientHandlers, GameController gameController) {
|
||||
this.clientSocket = clientSocket;
|
||||
this.clientHandlers = clientHandlers;
|
||||
this.gameController = gameController;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
public void run(){
|
||||
clientLoop();
|
||||
}
|
||||
private void clientLoop() {
|
||||
try {
|
||||
|
||||
private void clientLoop(){
|
||||
try{
|
||||
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
||||
synchronized (out) {
|
||||
synchronized(out){
|
||||
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
}
|
||||
catch(IOException e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
String s = "";
|
||||
try{
|
||||
while ((s = in.readLine()) != null) {
|
||||
synchronized(out){
|
||||
System.out.println(s);
|
||||
out.println(s.toUpperCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
private void notifyEvent(Object event) {
|
||||
synchronized (out) {
|
||||
|
||||
public void notifyEvent(Object event) {
|
||||
synchronized(out){
|
||||
out.println(event.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,16 +37,15 @@ public class TCPServer {
|
||||
|
||||
try{
|
||||
clientSocket = serverTCP.accept();
|
||||
if(!gameController.addPlayer(clientSocket.getInputStream().toString()) || ConnectedPlayers >= clientHandlers.size()){
|
||||
if(!gameController.addPlayer(clientSocket.getInputStream().toString()) || ConnectedPlayers > gameController.getModel().getNPlayers()){
|
||||
clientSocket.close();
|
||||
System.out.println("Player already present or username is invalid. Connection terminated.\n");
|
||||
System.out.println("Invalid parameters. Connection terminated.\n");
|
||||
}
|
||||
}
|
||||
catch (IOException e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
|
||||
System.out.println("Accepted");
|
||||
ConnectedPlayers++;
|
||||
ClientHandler clientHandler = new ClientHandler(clientSocket, clientHandlers, gameController);
|
||||
@@ -56,8 +55,12 @@ public class TCPServer {
|
||||
}
|
||||
}
|
||||
|
||||
private TCPServer(GameController gameController, int port) {
|
||||
private TCPServer(GameController gameController, int port){
|
||||
this.port = port;
|
||||
this.gameController = gameController;
|
||||
}
|
||||
|
||||
public void broadcastUpdate(Object event){
|
||||
clientHandlers.forEach((x) -> x.notifyEvent(event));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user