Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SocketServer {
- public ServerSocket server;
- public static HashMap<Integer, PrintWriter> listOfClients;
- public int id=0;
- /**
- * Wait for Sockets from clients
- */
- public void listenToClients() {
- // Never stop waiting!
- while (true) {
- try {
- // Accept socket from this client
- Socket clientSocket = server.accept();
- // Add PrintWriter (from client) to array
- PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
- listOfClients.put(id, writer);
- // Create and start new thread for this client
- Thread clientThread = new Thread(new ClientHandler(clientSocket, id));
- clientThread.start();
- Logger.out("[Client#" + id + "] connected.");
- // Increase ID
- id++;
- } catch (IOException e) {
- Logger.out("Can't listen to client(s)! Error code: 002");
- e.printStackTrace();
- }
- }
- }
- /**
- * Runs the SocketServer
- * @return
- */
- public boolean runServer() {
- try {
- // Start serversocket
- server = new ServerSocket(5555);
- Logger.out("Server started.");
- Logger.out("Waiting for clients to connect...");
- // Initialize PrintWriter (from clients) list
- listOfClients = new HashMap<Integer, PrintWriter>();
- return true;
- } catch (IOException e) {
- Logger.out("Server can not be started! Error code: 001");
- e.printStackTrace();
- return false;
- }
- }
- /**
- * Sends a message to all connected clients
- * @param message
- */
- public static void sendToAllClients(String message) {
- // Go through list and send message to all clients
- for(PrintWriter writer : listOfClients.values()) {
- writer.println(message);
- writer.flush();
- }
- }
- /**
- * Sends a message to a specific client
- * @param recieverID
- * @param message
- */
- public static void sendToClient(int recieverID, String message) {
- //Get client from list and send message
- PrintWriter writer = listOfClients.get(recieverID);
- writer.println(message);
- writer.flush();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement