Each client contains a fixed id how would I add this id to the server so that I can 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 is very simple and as you can see I tried to do something for ip but I realized that it would conflict later and it would have to be by same id passed by the client