Comunicación cliente-servidor-cliente mediante Sockets
Estoy creando una pequeña aplicación de chat en la que el cliente A quiere enviar algo al cliente C con el servidor B en medio. En primer lugar, ¿es este un enfoque correcto para el problema? Puedo enviar y recibir datos desde y hacia un servidor, pero está limitado solo al cliente. Por ejemplo, si el Cliente A envía datos al servidor B y el Cliente C envía datos al servidor B, entonces puedo enviar datos a A y C como un servidor de eco. Pero lo que quiero es reenviar los datos provenientes del Cliente A al Cliente C a través del servidor B.
El siguiente es el código del servidor:
<code>public class Server { public static void main(String[] args) { int port = 666; //random port number try { ServerSocket ss = new ServerSocket(port); System.out.println("Waiting for a client...."); System.out.println("Got a client :) ... Finally, someone saw me through all the cover!"); System.out.println(); while(true) { Socket socket = ss.accept(); SSocket sSocket = new SSocket(socket); Thread t = new Thread(sSocket); t.start(); System.out.println("Socket Stack Size-----"+socketMap.size()); } } catch (Exception e) { } } } class SSocket implements Runnable { private Socket socket; public SSocket(Socket socket) { this.socket = socket; } @Override public void run() { try { InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); DataInputStream dIn = new DataInputStream(in); DataOutputStream dOut = new DataOutputStream(out); String line = null; while (true) { line = dIn.readUTF(); System.out.println("Recievd the line----" + line); dOut.writeUTF(line + " Comming back from the server"); dOut.flush(); System.out.println("waiting for the next line...."); } } catch (Exception e) { } } } </code>
El código del cliente es:
<code>public class Client { public static void main(String[] args) { int serverPort = 666; try { InetAddress inetAdd = InetAddress.getByName("127.0.0.1"); Socket socket = new Socket(inetAdd, serverPort); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); DataInputStream dIn = new DataInputStream(in); DataOutputStream dOut = new DataOutputStream(out); BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Type in something and press enter. Will send it to the server and tell ya what it thinks."); System.out.println(); String line = null; while (true) { line = keyboard.readLine(); System.out.println("Wrinting Something on the server"); dOut.writeUTF(line); dOut.flush(); line = dIn.readUTF(); System.out.println("Line Sent back by the server---" + line); } } catch (Exception e) { } } } </code>