Advertisement
zgillis

Client.java

Jul 11th, 2012
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.*;
  4.  
  5. public class Client implements Runnable
  6. {
  7.     static Collection<Socket> users;
  8.     Socket clientSocket = null;
  9.     BufferedReader netInput;
  10.     PrintWriter netOutput;
  11.  
  12.     public Client(Socket ClientSocket)
  13.     {
  14.         clientSocket = ClientSocket;
  15.     }
  16.  
  17.     public void run()
  18.     {
  19.         try
  20.         {
  21.             netInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  22.             System.out.println("Input stream initialized.");
  23.             netOutput = new PrintWriter(clientSocket.getOutputStream());
  24.             System.out.println("Output stream initialized.");
  25.             netOutput.println("Welcome to the Nexo Relay Server!\nType things and have them echoed back at you.");
  26.             netOutput.flush();
  27.             users.add(clientSocket);
  28.             String cData = "";
  29.             while((cData = netInput.readLine()) != null)
  30.             {
  31.                 System.out.println(cData);
  32.                 //netOutput.println("ECHO: " + cData);
  33.                 sendToAll(cData);
  34.                 netOutput.flush();
  35.             }
  36.             users.remove(clientSocket);
  37.             System.out.println("Client disconnected.");
  38.         }
  39.         catch(Exception e){e.printStackTrace();}
  40.     }
  41.  
  42.     public static void sendToAll(String message) throws IOException
  43.     {
  44.         Iterator<Socket> clientIterator = users.iterator();
  45.         PrintWriter tempWriter;
  46.         Socket tempSocket;
  47.         while(clientIterator.hasNext())
  48.         {
  49.             tempSocket = clientIterator.next();
  50.             tempWriter = new PrintWriter(tempSocket.getOutputStream());
  51.             tempWriter.println("DATA FROM " + tempSocket.getRemoteSocketAddress()  + ": " + message);
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement