Advertisement
AngelovskiK

Оперативни Системи Лабс 2-4 Chat Room

Jun 26th, 2019
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.76 KB | None | 0 0
  1. //СЕРВЕР СТРАНА, КЛИЕНТ ПОДОЛЕ
  2.  
  3. package labs2.com;
  4.  
  5. import java.io.*;
  6. import java.net.ServerSocket;
  7. import java.net.Socket;
  8. import java.util.concurrent.ConcurrentHashMap;
  9.  
  10. public class TCPServer {
  11.  
  12.     private ServerSocket server;
  13.     private static ConcurrentHashMap<Integer, Socket> activeConnections;
  14.  
  15.     class ServerWorkerThread extends Thread {
  16.         Socket client;
  17.         DataInputStream reader;
  18.  
  19.         ServerWorkerThread(Socket client) throws IOException {
  20.             this.client = client;
  21.             reader = new DataInputStream(client.getInputStream());
  22.         }
  23.  
  24.         @Override
  25.         public void run() {
  26.             // todo: Handle listening to messages
  27.             String line = null;
  28.             try {
  29.                 while (!(line = reader.readUTF()).isEmpty()) {
  30.                     if(line.startsWith("END:")) {
  31.                         // izvadi go END: od porakata za da se dobie ID-to
  32.                         endConnection(Integer.parseInt(line.substring(4)));
  33.                     }else {
  34.                         String[] split = line.split(":");
  35.                         String targetSubstring = split[split.length - 1];
  36.                         Integer target = Integer.parseInt(targetSubstring);
  37.                         // izvadi go Id-to od krajot na porakta + 1 za dvete tocki
  38.                         String message = line.substring(0, line.length() - (targetSubstring.length() + 1));
  39.                         // pisi na target-ot so dataoutputstream
  40.                         new DataOutputStream(getConnection(target).getOutputStream()).writeUTF(message);
  41.                     }
  42.                 }
  43.             }catch (IOException e) {
  44.                 e.printStackTrace();
  45.             }
  46.         }
  47.     }
  48.  
  49.     // todo: Get the required connection
  50.     public Socket getConnection(int id) {
  51.         return activeConnections.get(id);
  52.     }
  53.  
  54.     // todo: Add connected client to the hash map
  55.     void addConnection(int id, Socket connection) {
  56.         activeConnections.put(id, connection);
  57.     }
  58.  
  59.     synchronized void endConnection(int id){
  60.         activeConnections.remove(id);
  61.     }
  62.  
  63.     //todo: Initialize server
  64.     TCPServer(int port) throws IOException {
  65.         server = new ServerSocket(port);
  66.     }
  67.  
  68.     // todo: Handle server listening
  69.     // todo: For each connection, start a separate
  70.     // todo: thread (ServerWorkerThread) to handle the communication
  71.     void listen() throws IOException {
  72.         Socket client;
  73.         while(true) {
  74.             client = server.accept();
  75.             String firstMessage = new DataInputStream(client.getInputStream()).readUTF();
  76.             // Izvadi go CONNECT: od prvata poraka za da se dobie id-to
  77.             addConnection(Integer.parseInt(firstMessage.substring(8)), client);
  78.             ServerWorkerThread workerThread = new ServerWorkerThread(client);
  79.             workerThread.start();
  80.         }
  81.     }
  82.  
  83.     public static void main(String[] args) throws IOException {
  84.         // todo: Start server
  85.         activeConnections = new ConcurrentHashMap<>();
  86.         TCPServer serverSocket = new TCPServer(8080);
  87.         serverSocket.listen();
  88.     }
  89. }
  90.  
  91. // КЛИЕНТ
  92.  
  93. package labs2.com;
  94.  
  95. import java.io.*;
  96. import java.net.Socket;
  97.  
  98. class ClientStarterWorkerThread extends Thread {
  99.  
  100.     private int ID;
  101.     private DataInputStream inputStream;
  102.  
  103.     public ClientStarterWorkerThread(int clientID, DataInputStream inputStream) {
  104.         this.ID = clientID;
  105.         this.inputStream = inputStream;
  106.     }
  107.  
  108.     @Override
  109.     public void run() {
  110.         // todo: Handle listening to messages
  111.         String line = null;
  112.         try {
  113.             while ((line = inputStream.readUTF()) != null) {
  114.                 System.out.println("Client " + ID + " has received message: " + line);
  115.             }
  116.         }catch (IOException e) {
  117.             e.printStackTrace();
  118.         }
  119.     }
  120. }
  121.  
  122. public class ClientStarer {
  123.  
  124.     private int ID;
  125.     Socket socket;
  126.     DataOutputStream writer;
  127.     DataInputStream inputStream;
  128.  
  129.     private ClientStarer(int id, String host, int port) throws IOException {
  130.         this.ID = id;
  131.         // todo: Connect to server and send client ID
  132.         socket = new Socket(host, port);
  133.         writer = new DataOutputStream(socket.getOutputStream());
  134.         inputStream = new DataInputStream(socket.getInputStream());
  135.  
  136.         writer.writeUTF("CONNECT:"+id);
  137.         listen();
  138.     }
  139.  
  140.     void sendMessage(int idReceiver, String message) throws IOException {
  141.         writer.writeUTF(message + ":" + idReceiver);
  142.     }
  143.  
  144.     // todo: end communication - send END to server
  145.     private void endCommunication() throws IOException {
  146.         writer.writeUTF("END:"+ID);
  147.     }
  148.  
  149.     private void listen() {
  150.         ClientStarterWorkerThread clientStarterWorkerThread = new ClientStarterWorkerThread(ID, inputStream);
  151.         clientStarterWorkerThread.start();
  152.     }
  153.  
  154.     public static void main(String[] args) throws IOException, InterruptedException {
  155.         ClientStarer client1 = new ClientStarer(1, "localhost", 8080);
  156.         ClientStarer client2 = new ClientStarer(2, "localhost", 8080);
  157.         ClientStarer client3 = new ClientStarer(3, "localhost", 8080);
  158.  
  159.         // Simulate chat
  160.         client1.sendMessage(2, "Hello from client 1");
  161.         Thread.sleep(1000);
  162.         client2.sendMessage(3, "Hello from client 2");
  163.         Thread.sleep(1000);
  164.         client1.sendMessage(3, "Hello from client 1");
  165.         Thread.sleep(1000);
  166.         client3.sendMessage(1, "Hello from client 3");
  167.         Thread.sleep(1000);
  168.         client3.sendMessage(2, "Hello from client 3");
  169.  
  170.         // Exit the chatroom
  171.         client1.endCommunication();
  172.         client2.endCommunication();
  173.         client3.endCommunication();
  174.     }
  175. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement