Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Server/Client Applet- Connection Reset Problem

  1. #1
    Junior Member
    Join Date
    May 2013
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Post Server/Client Applet- Connection Reset Problem

    Hi,

    I'm wondering can anyone help with a problem I'm having. Basically I'm making a Chat applet that allows clients to connect to a server and exchange messages. I have the messages being exchanged fine but whenever a client closes the connection I keep getting a

    java.net.SocketException: Connection reset Error

    The program is meant to keep track of the number of clients connected and update the the command line every time a client joins or leaves the Server.

    My code is attached below. Any help would be greatly appreciated!
    Thanks!
    import java.net.*;
    import java.io.*;
    import java.util.*;
     
    public class ChatServerThread extends Thread {
        private Socket socket = null;
        private String name;
        private String inputLine;
        private ArrayList <ChatServerThread> clientList;
        private PrintWriter out; 
        private BufferedReader in;
     
        //Constructor takes a socket and Arraylist of connected clients
        //as parameters
        public ChatServerThread(Socket socket,ArrayList <ChatServerThread> clientList) {
        	super("ChatServerThread");
        	this.socket = socket;
        	this.clientList = clientList;
        }
     
        //Broadcast the message to all connected clients
        //Not synchronized because I synchronized blocks where it is used
        public void sendToAll(String message){
        	for(ChatServerThread c: clientList){
    				c.out.println(message);				
    		}
        }
        public void run(){
     
        	try {
        			//Create input/output streams
    				out = new PrintWriter(socket.getOutputStream(), true);
    				in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    				//Read in client name
    				name = in.readLine();
    				//let everyone know user has joined
    				synchronized(this){
    					sendToAll( name + " has joined the chatroom ....\n");
     
    				}
    				//If user wants to leave break and close thread
    				while ((inputLine = in.readLine()) != null) {
    					//broadcast message to all
    					synchronized(this){
    						sendToAll(name+" says: "+ inputLine);
    					}
    				}
    				sendToAll( name + " has left the chatroom ....\n");
    				//Tidy up
    				synchronized(this){
    					clientList.remove(currentThread());
    				}
    				System.out.println("Clients :" +clientList.size() + "\n");
    				out.close();
    				in.close();
    				socket.close();
     
     
            } catch (IOException e) {
           		 e.printStackTrace();
        	}
    	}
    }
     
    //-------------------------------------------------------------------------------------//
    import java.net.*;
    import java.io.*;
    import java.util.*;
     
     
    public class ChatServer {
        public static void main(String[] args) throws IOException {
            ServerSocket serverSocket = null;
            Socket clientSocket = null;
     
            //Arraylist to hold all connected clients
            ArrayList <ChatServerThread> clientList = new ArrayList<>();
            final int PORT = 7777;
            boolean listening = true;
     
            try {
            	//Set up server socket
                serverSocket = new ServerSocket(PORT);
                System.out.println("Server now listening on port: " + PORT);
            } catch (IOException e) {
                System.err.println("Could not listen on port:" + PORT);
                System.exit(-1);
            }
     
    		//Loop to listen for and connect new clients, 
            while (listening){
    			try{
    				clientSocket = serverSocket.accept();
    				ChatServerThread client = new ChatServerThread
    				(clientSocket,clientList);
    				//add client to clientList and start the thread
    				clientList.add(client);
    				System.out.println("Clients :" + clientList.size() + "\n");
    				client.start();
     
    			} catch (IOException e) {}
    		}
     
            serverSocket.close();
        }
    }
     
    //-------------------------------------------------------------------------------------//
    Attached Files Attached Files


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Server/Client Applet- Connection Reset Problem

    The connection between the server and the client is being interrupted unexpectedly.
    Where is the client code? How does the client tell the server that the client wishes to terminate the connection?
    Make sure the client properly notifies the server about the upcoming disconnect before pulling the plug.
    Then make sure the server can handle it if (really "if" means "when") the client is disconnected unintentionally. For example when power is unexpectedly disconnected.

  3. The Following User Says Thank You to jps For This Useful Post:

    CD8ED (May 16th, 2013)

  4. #3
    Junior Member
    Join Date
    May 2013
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Server/Client Applet- Connection Reset Problem

    Hi jps,
    Many thanks for your reply! The applet is an assignment for college and we were given the code for the applet and chatclient. The code is below and unfortunately can't be modified as per the brief of the assignment. So I guess I'm asking is there anyway that the server can receive the close notification from the client and handle the close properly on the server side?

    /* Our chat client */
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
     
    class ChatClient extends Panel implements Runnable
    {
        /* Display */
        private TextField textfield = new TextField();
        private TextArea textarea = new TextArea();
        private Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
     
        /* Communication */
        private Socket s;
        private PrintWriter pw;
        private BufferedReader br;
     
        public ChatClient(String host, int port, String nickname) {
     
    	/* Set up display */
    	setLayout(new BorderLayout());
            textarea.setFont(font);
            textfield.setFont(font);
    	add(BorderLayout.SOUTH, textfield);
    	add(BorderLayout.CENTER, textarea);
     
    	/* Associate sendChat with textfield callback */
    	textfield.addActionListener(new ActionListener() {
    		public void actionPerformed(ActionEvent e) {
    		    sendChat(e.getActionCommand());
    		}
    	    });
     
    	try {
    	    s = new Socket(host, port);
    	    pw = new PrintWriter(s.getOutputStream(), true);
    	    br = new BufferedReader(new InputStreamReader(s.getInputStream()));
     
    	    /* Send nickname to chat server */
    	    pw.println(nickname);
     
    	    /* Become a thread */
    	    new Thread(this).start();
    	} catch (IOException e) {System.out.println(e);}
        }
     
        /* Called whenever user hits return in the textfield */
        private void sendChat(String message) {
    	    pw.println(message);
    	    textfield.setText("");
        }
     
        /* Add strings from chat server to the textarea */
        public void run() {
     
    	String message;
     
    	try {
    	    while (true) {
    		message = br.readLine();
    		textarea.append(message + "\n");
    	    }
    	} catch (IOException e) {System.out.println(e);}
        }
    }
     
    public class ChatApplet extends Applet
    {
        public void init() {
     
    	/* Retrieve parameters */
    	int port = Integer.parseInt(getParameter("port"));
    	String host = getParameter("host");
    	String nickname = getParameter("nickname");
     
    	/* Set up display */
    	setLayout(new BorderLayout());
    	add(BorderLayout.CENTER, new ChatClient(host, port, nickname));
        }
    }

  5. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Server/Client Applet- Connection Reset Problem

    Quote Originally Posted by CD8ED View Post
    So I guess I'm asking is there anyway that the server can receive the close notification from the client and handle the close properly on the server side?
    Yes. This is basically what I was saying in post #2.
    The client (when the client decides to close their end) should notify the server that the client wishes to close. The server will have to determine if the signal to close has been sent. This is one thing you need to do.
    The second thing you need to do is handle the case(s) where the connection is unexpectedly interrupted. That exception will climb to the top of the stack and play king of the hill on your server if you don't do something about it. You can't rely on always getting that ending message from any client.

  6. #5
    Junior Member
    Join Date
    May 2013
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Server/Client Applet- Connection Reset Problem

    Thanks again jps, I appreciate the answers/advice! Will try and tackle this tomorrow....... cramming for an exam at the minute Thanks again!

Similar Threads

  1. Replies: 0
    Last Post: May 31st, 2012, 06:35 PM
  2. ...CONNECTION OF CLIENT AND SERVER RUNNING ON DIFFERENT COMPUTERS
    By baraka.programmer in forum Java Networking
    Replies: 1
    Last Post: August 9th, 2011, 08:11 AM
  3. Replies: 0
    Last Post: May 10th, 2011, 08:02 AM
  4. Replies: 0
    Last Post: February 24th, 2011, 06:31 AM
  5. problem with closing connection to client socket
    By sunitha in forum Java Networking
    Replies: 1
    Last Post: December 11th, 2010, 04:28 AM