Client.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package com.company;
  2. import javax.xml.crypto.Data;
  3. import java.io.*;
  4. import java.net.Socket;
  5. import java.util.List;
  6. public class Client extends Thread {
  7. // Сокет текущего клиента
  8. private Socket socket;
  9. // Список всех подключенных слиентов
  10. private List<Client> clientList;
  11. public static int READ_BUFFER_SIZE = 1024;
  12. public Client(Socket socket, List<Client> clientList) throws IOException {
  13. this.socket = socket;
  14. this.clientList = clientList;
  15. }
  16. public Socket getSocket() {
  17. return socket;
  18. }
  19. @Override
  20. public void run() {
  21. while (!isInterrupted()) {
  22. try {
  23. ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
  24. Transport t = (Transport) ois.readObject();
  25. for (Client client : clientList) {
  26. if (client.socket != this.socket) {
  27. ObjectOutputStream coos = new ObjectOutputStream(client.socket.getOutputStream());
  28. coos.writeObject(t);
  29. coos.flush();
  30. }
  31. }
  32. System.out.print("\033[1;31m\033[40m " + t.Name + ": \u001B[0m ");
  33. System.out.println(t.Message);
  34. } catch (IOException | ClassNotFoundException exception) {
  35. System.out.println(exception.getMessage());
  36. clientList.remove(this);
  37. System.out.println("Disconnected user " + socket.getRemoteSocketAddress().toString());
  38. try {
  39. socket.close();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. return;
  44. }
  45. }
  46. }
  47. }