I have a server/client written. At the moment it's replying to individual clients (User one receives user one's post only) and I need multiple users to receive all posts.
Server
import java.net.*; import java.io.*; import java.util.*; class ServerThread extends Thread{ private Socket socket; ServerThread(Socket socket){ this.socket = socket; } public void run(){ try { String message = null; PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); br.readLine(); while((message = br.readLine()) != null){ // while messages read them pw.println(message); } socket.close(); } catch(IOException e) { System.out.println("Client disconnected"); } } } // The server public class Server{ public static final int PORT = 7777; public ArrayList<Socket> connections = new ArrayList<>(); public static void main(String[] args) throws IOException { new Server().run(); } public void run() throws IOException{ ServerSocket serverSocket = new ServerSocket(PORT); // wait for request from PORT System.out.println("Server is listening for connections"); while(true){ Socket socket = serverSocket.accept(); // listen and accept connection connections.add(socket); new ServerThread(socket).start(); System.out.println("Client " + connections.size()); } } }
Client
import java.net.*; import java.io.*; import java.util.*; public class Client{ public static void main(String[] args) throws UnknownHostException, IOException { String name = args[0]; Socket socket = new Socket("localhost", 7777); BufferedReader brFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); pw.println(name); BufferedReader brFromCmd = new java.io.BufferedReader(new InputStreamReader(System.in)); while(true){ String readInput = brFromCmd.readLine(); pw.println(name + ": " + readInput); System.out.println(brFromClient.readLine()); } } }
Any help is greatly appreciated..