R
R
Roman2015-06-25 16:51:03
Java
Roman, 2015-06-25 16:51:03

Chat in Java, sending a message to a specific client, how to do it?

Good day!
There is a code in Java where there are 4 classes "constant" - the port of the server is determined, "Server" - the chat server receives and sends messages, "Client" - the connection to the server receives and sends messages "Main" - the main class that starts either the server or the client (weight code is given below). Everything works fine thanks to the author (the author is not me, the code was found on the net).
But there is a need to make it possible to choose who to send a message to (preferably using sockets). Roughly speaking, the server has a list of connected clients and when it is accessed by CLIENT1, the server gives only the socket (IP + Port) of CLIENT2 and already CLIENT1 and CLIENT2 communicate without the help of the server.

PS: Honestly, I yandexnul and googled,


package main;  
public abstract class Const {

  public static final int Port = 8309;
  
}


package main;

import java.util.Scanner; 
import server.Server; 
import client.Client; 


public class Main {


  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    System.out.println("Работать как Клиент или Сервер? (S(erver) / C(lient))");
    while (true) {
      char answer = Character.toLowerCase(in.nextLine().charAt(0)); 
      if (answer == 's') {
        new Server();
        break;
      } else if (answer == 'c') {
        new Client();
        break;
      } else {
        System.out.println("Fehler");
      }
    }
  }

}


package server;

import java.io.BufferedReader;
import java.io.IOException;   
import java.io.InputStreamReader;  
import java.io.PrintWriter; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import main.Const;


public class Server {

  
  
  private List<Connection> connections = 
      Collections.synchronizedList(new ArrayList<Connection>());
  private ServerSocket server;

  
  public Server() {
    try {
      server = new ServerSocket(Const.Port);

      while (true) {
        Socket socket = server.accept(); 
        
        Connection con = new Connection(socket);
        connections.add(con);
        
        con.start();

      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      closeAll();
    }
  }


  private void closeAll() {
    try {
      server.close();
            
      synchronized(connections) {
        Iterator<Connection> iter = connections.iterator();
        while(iter.hasNext()) {
          ((Connection) iter.next()).close();
        }
      }
    } catch (Exception e) {
      System.err.println("Fehler!");
    }
  }

  private class Connection extends Thread {
    private BufferedReader in;
    private PrintWriter out;
    private Socket socket;
  
    private String name = "";
  
  
    public Connection(Socket socket) {
      this.socket = socket;
  
      try {
        in = new BufferedReader(new InputStreamReader(
            socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream(), true);
  
      } catch (IOException e) {
        e.printStackTrace();
        close();
      }
    }
  

    @Override
    public void run() {
      try {
        name = in.readLine();
        
        synchronized(connections) {
          Iterator<Connection> iter = connections.iterator();
          while(iter.hasNext()) {
            ((Connection) iter.next()).out.println(name + " cames now");
          }
        }
        
        String str = "";
        while (true) {
          str = in.readLine();
          if(str.equals("exit")) break;
          
          
          synchronized(connections) {
            Iterator<Connection> iter = connections.iterator();
            while(iter.hasNext()) {
              ((Connection) iter.next()).out.println(name + ": " + str);
            }
          }
        }
        
        synchronized(connections) {
          Iterator<Connection> iter = connections.iterator();
          while(iter.hasNext()) {
            ((Connection) iter.next()).out.println(name + " has left");
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        close();
      }
    }
  
    
    public void close() {
      try {
        in.close();
        out.close();
        socket.close();
  
        
        connections.remove(this);
        if (connections.size() == 0) {
          Server.this.closeAll();
          System.exit(0);
        }
      } catch (Exception e) {
        System.err.println("Fehler!");
      }
    }
  }
}


package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

import main.Const;


public class Client {
  private BufferedReader in;
  private PrintWriter out;
  private Socket socket;


  public Client() {
    Scanner scan = new Scanner(System.in);

    System.out.println("IP Adresse (Localhost 127.0.0.1).");
    System.out.println("Format: xxx.xxx.xxx.xxx");

    String ip = scan.nextLine();

    try {
      
      socket = new Socket(ip, Const.Port);
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      out = new PrintWriter(socket.getOutputStream(), true);

      System.out.println("Имя в чате");
      out.println(scan.nextLine());

      
      Resender resend = new Resender();
      resend.start();

      
      String str = "";
      while (!str.equals("exit")) {
        str = scan.nextLine();
        out.println(str);
      }
      resend.setStop();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      close();
    }
  }

  
  private void close() {
    try {
      in.close();
      out.close();
      socket.close();
    } catch (Exception e) {
      System.err.println("Fehler!");
    }
  }


  private class Resender extends Thread {

    private boolean stoped;
    
    
    public void setStop() {
      stoped = true;
    }

    
    @Override
    public void run() {
      try {
        while (!stoped) {
          String str = in.readLine();
          System.out.println(str);
        }
      } catch (IOException e) {
        System.err.println("Fehler");
        e.printStackTrace();
      }
    }
  }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton, 2015-06-26
@Gokudera

I support pi314
So, as far as I can see, both the client and the server are already written.
List - make a Map and get connection by Id
instead

Iterator<Connection> iter = connections.iterator();
            while(iter.hasNext()) {
              ((Connection) iter.next()).out.println(name + ": " + str);
            }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question