Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Server {
- int port;
- ServerSocket server=null;
- Socket socket=null;
- ExecutorService exec = null;
- ArrayList clients = new ArrayList();
- DataOutputStream dos=null;
- public static void main(String[] args) throws IOException {
- Server serverobj=new Server(2000);
- serverobj.startServer();
- }
- Server(int port){
- this.port=port;
- exec = Executors.newFixedThreadPool(3);
- }
- public void startServer() throws IOException {
- server=new ServerSocket(2000);
- System.out.println("Server running");
- while(true){
- socket=server.accept();
- dos = new DataOutputStream(socket.getOutputStream());
- clients.add(dos);
- ServerThread runnable= new ServerThread(socket,new ArrayList<>(clients),this);
- exec.execute(runnable);
- }
- }
- private static class ServerThread implements Runnable {
- Server server=null;
- Socket socket=null;
- BufferedReader brin;
- Iterator it=null;
- Scanner sc=new Scanner(System.in);
- String str;
- ServerThread(Socket socket, ArrayList clients ,Server server ) throws IOException {
- this.socket=socket;
- this.server=server;
- System.out.println("Connection successful with "+socket);
- brin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
- it = clients.iterator();
- }
- @Override
- public void run() {
- try{
- while ((str = brin.readLine()) != null) {
- while (it.hasNext()) {
- try{
- DataOutputStream dost=(DataOutputStream) it.next();
- dost.writeChars(str);
- dost.flush();
- }
- catch(IOException ex){
- System.out.println("Error 1 "+ex);
- }
- }
- }
- brin.close();
- socket.close();
- }
- catch(IOException ex){
- System.out.println("Error 2 "+ex);
- }
- }
- }
- }
- public class Client1 {
- public static void main(String args[]) throws IOException{
- String str;
- Socket socket=new Socket("127.0.0.1",2000);
- PrintStream prout=new PrintStream(socket.getOutputStream());
- BufferedReader bread=new BufferedReader(new InputStreamReader(System.in));
- BufferedReader dis=new BufferedReader(new InputStreamReader(socket.getInputStream()));
- while(true){
- System.out.println("Send to others:");
- str=bread.readLine();
- prout.println(str);
- }
- }
- }
- public class Client2 {
- public static void main(String args[]) throws IOException{
- String str;
- Socket socket=new Socket("127.0.0.1",2000);
- BufferedReader dis=new BufferedReader(new InputStreamReader(socket.getInputStream()));
- while(true){
- str=dis.readLine();
- System.out.print("Message: "+str+"n");
- }
- }
- }
Add Comment
Please, Sign In to add comment