Results 1 to 4 of 4
  1. #1
    Vampire5 is offline Member
    Join Date
    Aug 2012
    Posts
    20
    Rep Power
    0

    Question Reading errors when disconnecting from server

    Not sure this is the best topic area to put this in, but I suppose. Anyways, I've been following a tutorials on some basic Java networking, and this one in particular is about how to make a console chat (link). The information seems to be outdated (I've replaced the stop() functions with interrupt() ), but it seems to be working so far (I'll attach my modified code, since I also added a little stuff of my own). However, when I try to quit the application, it gives me errors on both the server and the client as follows:

    server:
    Java Code:
    37974 error reading: Stream closed
    (37974 is the ID)

    client:
    Java Code:
    Listening error: Socket closed

    If you look in the code, you can see where these problems occur. I'm sort of new to networking in general, so I don't understand, I thought the connection had already been terminated.

    Thanks!

    Here's the modified code I wrote since I can't upload it:

    Java Code:
    import java.net.*;
    import java.io.*;
    import java.lang.*;
    
    public class Client implements Runnable {
    	private Socket socket = null;
    	private ClientThread cThread = null;
    	private DataOutputStream streamOut = null;
    	private BufferedReader console = null;
    	private Thread thread = null;
    
    	public static void main(String[] args) {
    		if(args.length != 2) {
    			System.out.println("Usage: java Client [server] [port]");
    		} else {
    			Client client = new Client(args[0], Integer.parseInt(args[1]));
    		}
    	}
    
    	public Client(String server, int port) {
    		try {
    			// Create a new socket connection
    			System.out.println("Connecting to server...");
    			socket = new Socket(server, port);
    			start();
    		} catch(UnknownHostException uhe) {
    			System.out.println("Host unknown: " + uhe.getMessage());
    		} catch(IOException e) {
    			System.out.println("Unknown exception: " + e.getMessage());
    		}
    	}
    
    	public void run() {
    		while(thread != null) {
    			try {
    				streamOut.writeUTF(console.readLine());
    				streamOut.flush();
    			} catch(IOException e) {
    				System.out.println("Sending error: " + e.getMessage());
    				stop();
    			}
    		}
    	}
    
    	public void handle(String msg) {
    		if(msg.equals("/quit")) {
    			System.out.println("Goodbye bye. Press RETURN to exit...");
    			stop();
    		} else {
    			System.out.println(msg);
    		}
    	}
    
    	private void start() throws IOException {
    		console = new BufferedReader(new InputStreamReader(System.in));
    		streamOut = new DataOutputStream(socket.getOutputStream());
    		
    		if(thread == null) {
    			cThread = new ClientThread(this, socket);
    			thread = new Thread(this);
    			thread.start();
    		}
    	}
    
    	public void stop() {
    		if(thread != null) {
    			thread.interrupt();
    			thread = null;
    		}
    
    		try {
    			if(console != null) { console.close(); }
    			if(streamOut != null) { streamOut.close(); }
    			if(socket != null) { socket.close(); }
    		} catch(IOException e) {
    			System.out.println("Error closing...");
    		}
    
    		cThread.close();
    		cThread.interrupt();
    	}
    }
    Java Code:
    import java.io.*;
    import java.net.*;
    
    public class ClientThread extends Thread {
    	private Socket socket = null;
    	private Client client = null;
    	private DataInputStream streamIn = null;
    
    	public ClientThread(Client _client, Socket _socket) {
    		client = _client;
    		socket = _socket;
    		open();
    		start();
    	}
    
    	public void open() {
    		try {
    			streamIn = new DataInputStream(socket.getInputStream());
    		} catch(IOException e) {
    			System.out.println("Error getting input stream: " + e);
    			client.stop();
    		}
    	}
    
    	public void close() {
    		try {
    			if(streamIn != null) { streamIn.close(); }
    		} catch(IOException e) {
    			System.out.println("Error closing input stream: " + e);
    		}
    	}
    
    	public void run() {
    		while(true) {
    			try {
    				client.handle(streamIn.readUTF());
    			} catch(IOException e) {
    				System.out.println("Listening error: " + e.getMessage());
    				client.stop();
    			}
    		}
    	}
    }
    Java Code:
    import java.net.*;
    import java.io.*;
    import java.util.*;
    
    public class Server implements Runnable {
    	// This can be changed for an ArrayList to avoid limits.
    	//private ServerThread clients[] = new ServerThread[50];
    	private ArrayList<ServerThread> clients = new ArrayList<ServerThread>();
    	private ServerSocket sSocket = null;
    	private Thread thread = null;
    	private int clientCount = 0;
    
    	public static void main(String[] args) {
    		if(args.length != 1) {
    			System.out.println("You are using the program incorrectly.");
    		} else {
    			Server server = new Server(Integer.parseInt(args[0]));
    		}
    	}
    
    	public Server(int port) {
    		try {
    			System.out.println("Binding to port " + port + "...");
    			// Try to open a port on the specified port number
    			sSocket = new ServerSocket(port);
    			System.out.println("Server started: " + sSocket);
    			start();
    		} catch(IOException e) {
    			System.out.println(e);
    		}
    	}
    
    	public void run() {
    		while(thread != null) {
    			try {
    				System.out.println("Waiting for clients...");
    				addThread(sSocket.accept());
    			} catch(IOException e) {
    				System.out.println("Acceptance error: " + e);
    				stop();
    			}
    		}
    	}
    
    	public void start() {
    		if(thread == null) {
    			thread = new Thread(this);
    			thread.start();
    		}
    	}
    
    	public void stop() {
    		if(thread != null) {
    			thread.interrupt();
    			thread = null;
    		}
    	}
    
    	public int findClient(int id) {
    		for(int i = 0; i < clientCount; i++) {
    			//if(clients[i].getID() == id) {
    			if(clients.get(i).getID() == id) {
    				return i;
    			}
    		}
    
    		return -1;
    	}
    
    	public synchronized void handle(int id, String input) {
    		if(input.equals("/quit")) {
    			//clients[findClient(id)].send("/quit");
    			clients.get(findClient(id)).send("/quit");
    			remove(id);
    		} else {
    			for(int i = 0; i < clientCount; i++) {
    				//if(clients[i].getID() != id) {
    				if(clients.get(i).getID() != id) {
    					//clients[i].send(id + ": " + input);
    					clients.get(i).send(id + ": " + input);
    				}
    			}
    		}
    	}
    
    	public synchronized void remove(int id) {
    		int pos = findClient(id);
    		if(pos >= 0) {
    			//ServerThread toTerminate = clients[pos];
    			ServerThread toTerminate = clients.get(pos);
    			System.out.println("Remove client thread: " + id + " at " + pos);
    			/**if(pos < clientCount - 1) {
    				for(int i = pos+1; i < clientCount; i++) {
    					clients[i-1] = clients[i];
    				}
    			}*/
    			clients.remove(pos);
    			clientCount--;
    			try {
    				toTerminate.close();
    			} catch(IOException e) {
    				System.out.println("Error closing thread: " + e);
    			}
    			toTerminate.interrupt();
    		}
    	}
    
    	public void addThread(Socket socket) {
    		clients.add(new ServerThread(this, socket));
    		try {
    			//clients[clientCount].open();
    			//clients[clientCount].start();
    			clients.get(clientCount).open();
    			clients.get(clientCount).start();
    			clientCount++;
    		} catch(IOException e) {
    			System.out.println("Error opening thread: " + e);
    		}
    
    		/**if(clientCount < clients.length) {
    			System.out.println("Client accepted: " + socket);
    			clients[clientCount] = new ServerThread(this, socket);
    			try {
    				clients[clientCount].open();
    				clients[clientCount].start();
    				clientCount++;
    			} catch(IOException e) {
    				System.out.println("Error opening thread: " + e);
    			}
    		} else {
    			System.out.println("Client refused: maximum " + clients.length + " reached.");
    		}*/
    	}
    }
    Java Code:
    import java.net.*;
    import java.io.*;
    
    public class ServerThread extends Thread {
    	private Server server = null;
    	private Socket socket = null;
    	private int id = -1;
    	private DataInputStream streamIn = null;
    	private DataOutputStream streamOut = null;
    
    	public ServerThread(Server _server, Socket _socket) {
    		super();
    		this.socket = _socket;
    		this.server = _server;
    		id = socket.getPort();
    	}
    
    	public void send(String msg) {
    		try {
    			streamOut.writeUTF(msg);
    			streamOut.flush();
    		} catch(IOException e) {
    			System.out.println(id + " Error sending: " + e.getMessage());
    			server.remove(id);
    			interrupt(); // We might need to call this from the Server class
    		}
    	}
    
    	public void run() {
    		System.out.println("Server thread " + id + " running.");
    		while(true) {
    			try {
    				server.handle(id, streamIn.readUTF());
    			} catch(IOException e) {
    				System.out.println(id + " error reading: " + e.getMessage());
    				server.remove(id);
    				interrupt(); // Same as the last interrupt
    			}
    		}
    	}
    
    	public void open() throws IOException {
    		streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    		streamOut = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
    	}
    
    	public void close() throws IOException {
    		if(socket != null) { socket.close(); }
    		if(streamIn != null) { streamIn.close(); }
    		if(streamOut != null) { streamOut.close(); }
    	}
    
    	public int getID() { return id; }
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default Re: Reading errors when disconnecting from server

    How are you debugging the code? Add some println() statements next to all the calls to a close() method so you can see when they are called and when the errors happen.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: Reading errors when disconnecting from server

    Hi,

    I see multiple issues:
    Calling interrupt is not stopping a thread. So the thread is still running and tries to read from the stream/socket that you closed from the other thread.
    Keep the responsibles! The thread who reads the stream is responsible for it. So just change the logic in a way like:
    - close just set a flag for the while loop.
    - while(true) is replaced with while (someflag)
    - after the while loop you close the streams

    And that a socket is closed can happen. If the connection was closed on the other side then you could get that exception. So you have to take care of that in your code.

    I hope these points help you a little bit.

    Konrad

  4. #4
    Vampire5 is offline Member
    Join Date
    Aug 2012
    Posts
    20
    Rep Power
    0

    Default Re: Reading errors when disconnecting from server

    Quote Originally Posted by kneitzel View Post
    Hi,

    I see multiple issues:
    Calling interrupt is not stopping a thread. So the thread is still running and tries to read from the stream/socket that you closed from the other thread.
    Keep the responsibles! The thread who reads the stream is responsible for it. So just change the logic in a way like:
    - close just set a flag for the while loop.
    - while(true) is replaced with while (someflag)
    - after the while loop you close the streams

    And that a socket is closed can happen. If the connection was closed on the other side then you could get that exception. So you have to take care of that in your code.

    I hope these points help you a little bit.

    Konrad
    Thanks, I just realized now that the run event never quit, I thought the interrupt did that. But yes, I changed it the way you told me and it seems to be working now. Thanks a lot to all of you!

Similar Threads

  1. Reading from text file errors ?!?!?!?!?!? Need Help
    By Asmicor in forum New To Java
    Replies: 6
    Last Post: 06-27-2013, 12:03 AM
  2. Java Errors Ubuntu Server 10.04
    By xb2003 in forum New To Java
    Replies: 1
    Last Post: 08-21-2012, 01:57 PM
  3. Need Help reading errors
    By sccot21 in forum New To Java
    Replies: 16
    Last Post: 04-21-2012, 08:05 PM
  4. Reading a TxtFile from a Server
    By Nigge in forum Networking
    Replies: 19
    Last Post: 02-18-2012, 03:17 AM
  5. Server.java Errors trying to build a chat
    By agfre44_9873 in forum Java Applets
    Replies: 2
    Last Post: 04-25-2009, 02:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •