3

i am trying to make a chat program. The problem i am having is that my loop in the EchoThread always thinks that the connection is true. I have tried to use if(s.isConnected() == false) but that didn't work also i tried to do if(s.isClosed() == true) if you can help thank you in advance. Here is my code

import java.io.*;
import java.net.*;
import java.util.ArrayList;

public class server {
public ObjectInputStream input;
public ServerSocket server;
public Socket s;
public ObjectOutputStream output;
public ArrayList<ObjectOutputStream> outputs = new ArrayList<ObjectOutputStream>();
public ArrayList<Socket> users = new ArrayList<Socket>();
public class Accept implements Runnable {
    public void run() {
        try {
            server = new ServerSocket(55555, 100);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while(true) {
            try {
                s = server.accept();
                new EchoThread(s).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
public class EchoThread extends Thread {
    private Socket s1;
    public EchoThread(Socket s) throws IOException {
        this.s1 = s;
    }
    public void run() {
        users.add(s1);
        try {
            outputs.add(new ObjectOutputStream(s1.getOutputStream()));
            newUser();
        } catch (IOException e) {
            System.out.println("Error 2");
        }
        while(s1.isConnected() == true) {
            // loops until socket looses connection
        }
        System.out.println("Disconnected");
        }
    }
public class check implements Runnable {

    public void run() {
    }

}
public void newUser() {
    try {
        for(ObjectOutputStream o: outputs) {
                o.writeObject(s.getInetAddress() + " Connected");
        }
    } catch (IOException e1) {
        System.out.println("Error 21");
    }
}
server() throws IOException {
    Thread t = new Thread(new Accept());
    t.start();
    Thread ch = new Thread(new check());
    ch.start();
    }
public static void main(String[] args) throws IOException {
    new server();
}
}
mardis7021
  • 61
  • 1
  • 1
  • 6

2 Answers2

5

you have to read this, you have to check with the read()method to check if it returns -1.

https://stackoverflow.com/a/10241044/964152

Community
  • 1
  • 1
Flm
  • 271
  • 1
  • 7
0
while(s1.isConnected() == true) {

This is not a valid loop. isConnected() is true because you accepted the socket, and it doesn't magically become false afterwards. When the client disconnects, you will get the appropriate end of stream indication from whichever read method you're calling.

user207421
  • 305,947
  • 44
  • 307
  • 483