Advertisement
Shailrshah

Broadcasting messages

Oct 18th, 2015
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.33 KB | None | 0 0
  1. /*Server.java*/
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.io.PrintWriter;
  5. import java.net.Socket;
  6. import java.net.ServerSocket;
  7. import java.util.Vector;
  8. public class Server extends Thread{
  9.     private Socket socket;
  10.     private static Vector<PrintWriter> writers = new Vector<PrintWriter>();
  11.     public Server(Socket socket) {
  12.         this.socket = socket;
  13.     }
  14.     public void run() {
  15.         try {
  16.             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  17.             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
  18.             out.println("SUBMITNAME");
  19.             String name = in.readLine();
  20.             System.out.println(name+" joined");
  21.             writers.add(out);
  22.             while (true) {
  23.                 String input = in.readLine();
  24.                 for (PrintWriter writer : writers)
  25.                     writer.println("MESSAGE " + name + ": " + input);
  26.             }
  27.         } catch (Exception e) {System.err.println(e);}
  28.     }
  29.     public static void main(String[] args) throws Exception {
  30.         ServerSocket serversocket = new ServerSocket(9001);
  31.         System.out.println("The server is running at port 9001.");
  32.         while (true)
  33.             new Server(serversocket.accept()).start();
  34.     }
  35. }
  36.  
  37. /*Client.java*/
  38. import java.io.BufferedReader;
  39. import java.io.InputStreamReader;
  40. import java.io.PrintWriter;
  41. import java.net.Socket;
  42. import java.util.Scanner;
  43. public class Client {
  44.     public static void main(String[] args) throws Exception {
  45.         Scanner sc = new Scanner(System.in);
  46.         Socket socket = new Socket("localhost", 9001);
  47.         BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  48.         PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
  49.         System.out.print("Enter your name: ");
  50.         String name = sc.nextLine();
  51.         while (true) {
  52.             String line = in.readLine();
  53.             if (line.startsWith("SUBMITNAME")) out.println(name);
  54.             else if (line.startsWith("MESSAGE"))
  55.                 System.out.println(line.substring(8));
  56.             if(name.startsWith("master")){
  57.                 System.out.print("Enter a message: ");
  58.                 out.println(sc.nextLine());
  59.             }
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement