Question: Please do not copy and paste code from ChatGTP. Edit the code I have provided with explanation in end if possible. thank you Implement the
Please do not copy and paste code from ChatGTP. Edit the code I have provided with explanation in end if possible. thank you
Implement the two following server-side activities for all connected clients (majority of the logic should be processed server-side and broadcasted/sent to all clients if/when applicable)
1. Coin toss command (random heads or tails)
Command should be something logical like flip or toss or coin or similar
The result should mention who did what and got what result (i.e., Bob Flipped a coin and got heads)
2. Dice roller given a command and text format of "roll #d#" (i.e., roll 2d6)
Command should be in the format of roll #d# (i.e., roll 1d10)
The result should mention who did what and got what result (i.e., Bob rolled 1d10 and got 7)
Code:
package Module4.Part3;
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
public class Server { int port = 3001; // connected clients private List
private void start(int port) { this.port = port; // server listening try (ServerSocket serverSocket = new ServerSocket(port);) { Socket incoming_client = null; System.out.println("Server is listening on port " + port); do { System.out.println("waiting for next client"); if (incoming_client != null) { System.out.println("Client connected"); ServerThread sClient = new ServerThread(incoming_client, this); clients.add(sClient); sClient.start(); incoming_client = null; } } while ((incoming_client = serverSocket.accept()) != null); } catch (IOException e) { System.err.println("Error accepting connection"); e.printStackTrace(); } finally { System.out.println("closing server socket"); } } protected synchronized void disconnect(ServerThread client) { long id = client.getId(); client.disconnect(); broadcast("Disconnected", id); } protected synchronized void broadcast(String message, long id) { if(processCommand(message, id)){
return; } // let's temporarily use the thread id as the client identifier to // show in all client's chat. This isn't good practice since it's subject to // change as clients connect/disconnect message = String.format("User[%d]: %s", id, message); // end temp identifier // loop over clients and send out the message Iterator
private boolean processCommand(String message, long clientId){ System.out.println("Checking command: " + message); if(message.equalsIgnoreCase("disconnect")){ Iterator
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
