Reputation: 635
I've been working on a chat room.
Multi Threaded Server accepts the clients
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
int port = 2345;
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for clients");
Thread thread = new Thread(){
public void run(){
while(true){
Socket socket;
try {
socket = server.accept();
gui.AddUserToList(socket);
ConnectionArray.add(socket);
ChatClient chat = new ChatClient(socket,gui);
Thread x = new Thread(chat);
x.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
thread.start();
}
catch(IOException error){
System.out.println(error);
}
}
});
When the connect button is pressed it will run an infinite loop to accept clients. For each client it connects, it ads it to a ListArray called AddUserToList.
A ChatClient is made and the object is passed in the Thread constructor.
public void isConnected(){
if(!socket.isConnected()){
for(int i = 1; i <= GUI.ConnectionArray.size(); i++){
if(GUI.ConnectionArray.get(i) == socket){
GUI.ConnectionArray.remove(i);
gui.updateList();
}
}
}
}
@Override
public void run() {
try
{
try
{
input = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream());
while(true)
{
isConnected();
if(!input.hasNext())
return;
message = input.nextLine();
for(int i = 1; i <= GUI.ConnectionArray.size(); i++){
Socket tmpSocket = (Socket) GUI.ConnectionArray.get(i-1);
PrintWriter tmpOut = new PrintWriter(tmpSocket.getOutputStream());
tmpOut.println(message);
tmpOut.flush();
//System.out.println("Sent");
}
}
}
finally
{
socket.close();
}
}
catch(IOException io){
System.out.println(io);
}
}
If there is are no messages coming then it should check the connection. When I disconnect on my client.
while(true)
{
isConnected();
if(!input.hasNext())
return;
This line should go back since nothing is being sent, so why does the program get stuck trying to listen on messages?
Is there really no way to close a socket? Because I need to remove the user/socket from the ArrayList and then update it to show me that there is no client connected.
Upvotes: 2
Views: 2398
Reputation: 311039
You need to check for the end of stream condition on all your reads and Scanner invocations. You aren't doing that anywhere. The isConnected()
method doesn't do that. It only tells you whether you ever connected this socket.. It doesn't magically become false when the peer disconnects. Neither does isClosed()
magically become true at that time.
Upvotes: 2