0

I am currently trying to take an ArrayList and fill it with sockets using .add, when the socket is passed into the constructor. When i run the debug, it looks like there is only ever 1 socket filling the ArrayList, and no more, even though I've opened like 6 client threads.

Server class

public static void main(String[] args) throws IOException
{
    final int PORT = 8888;
    ServerSocket server = new ServerSocket(PORT);
    System.out.println("Waiting...");

    while(true)
    {
        Socket s = server.accept();
        System.out.println("Client connected");
        Service service = new Service(s);
        Thread t = new Thread(service);
        t.start();
    }

Service class

 public class Service implements Runnable
{
private Socket s;
private Scanner in;
private PrintWriter out;
private ArrayList<Socket> sockets = new ArrayList<Socket>();

public Service(Socket aSocket)
{
    s = aSocket;
    sockets.add(s);
}

1 Answer 1

3

It's because you create a new Service every loop => you will have 6 Service objects with one arrayList in each containing each objects socket. If you want your arrayList to contain all clients / sockets, you will have to have this list in your server class. Also it's rarely a good idea for your clients to know about all other clients. I also suggest putting in a Thread.sleep(100) in your main method (server), otherwise it will take up a lot of your precessing power.

public static void main(String[] args) throws IOException
{
    final int PORT = 8888;
    ServerSocket server = new ServerSocket(PORT);
    System.out.println("Waiting...");
    private ArrayList<Socket> sockets = new ArrayList<Socket>();

    while(true)
    {
        Thread.sleep(100);
        Socket s = server.accept();
        System.out.println("Client connected");
        Service service = new Service(s);
        Thread t = new Thread(service);
        t.start();
        sockets.add(s);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.