1
Each client contains a fixed id would have as I amnesze that id to the server to then be able to send messages to clients with specific ids?
Server:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Server {
List<PrintWriter> writers = new ArrayList<>();
List<Thread> clients = new ArrayList<>();
Thread t;
public Server() {
ServerSocket server;
try {
server = new ServerSocket(6000);
while (true) {
Socket socket = server.accept();
t = new Thread(new listenClient(socket));
t.setName(socket.getInetAddress().toString());
clients.add(t);
t.start();
PrintWriter p = new PrintWriter(socket.getOutputStream());
writers.add(p);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendAll(String text) {
for (PrintWriter w : writers) {
w.println(text);
w.flush();
}
}
private class listenClient implements Runnable {
Scanner scan;
public listenClient(Socket socket) {
try {
scan = new Scanner(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
String text;
while ((text = scan.nextLine()) != null) {
sendAll(text);
System.out.println(text);
}
}
}
public static void main(String[] args) {
new Server();
}
This very simple and as you can see I tried to do something by ip but I realized that it would give conflict more forward and would have to be by id even passed by the client