Search code examples
javasocketstcp

Java Client-Server application throws "java.net.SocketException: Connection reset" exception


I was trying to create a Client-Server application where the client generates a random number and sends to the server n strings. The connection is closed sending the string "BYE". After that the server has to calculate the total length of the received strings and print it.

The problem is that when my client tries to connect to the server this one throws "java.net.SocketException: Connection reset" exception and crashes.

Here's my Client code:


import java.net.*;
import java.io.*;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ClientStringa {

    public static void main(String[] args) {
        try{
            Socket socket = new Socket("localhost", 5555);
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            Random r = new Random();

            int N = r.nextInt(100);

            for(int i=1;i<=N;i++){
                out.println("String" +i);    
            }
            out.flush();
        }
        catch (IOException ex) {
            Logger.getLogger(ClientStringa.class.getName()).log(Level.SEVERE, null, ex);    
        }
    }
}

My Server code:


import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ServerStringa {
    public static void main(String[] args) {
        try {
            ServerSocket socket = new ServerSocket(5555);

            while(true){
                System.out.println("Waiting for client connections...");
                Socket client = socket.accept();    //connessione dei client
                ThreadStringa thread = new ThreadStringa(client);
                thread.start();             
            }

        } catch (IOException ex) {
            Logger.getLogger(ServerStringa.class.getName()).log(Level.SEVERE, null, ex);
        }   
    }  
}

And my Thread code (since the server must be able to answer more clients):


import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadStringa extends Thread{
    Socket client;

    public ThreadStringa(Socket client) {
        this.client = client;
    }

    public void run(){
        try {
           // DataInputStream input = new DataInputStream(client.getInputStream());
            String message;
            int sum=0;

            InputStream input = client.getInputStream();
            InputStreamReader input2 = new InputStreamReader(input);
            BufferedReader in = new BufferedReader(input2);

            while((message= in.readLine()) != null){
                if(message.equals("BYE")){
                    break;
                }
                sum+=message.length();              
            }

            System.out.println("Total length of received strings: " + sum);   
            input.close();
            client.close();
        } 
        catch (IOException ex) {
            Logger.getLogger(ThreadStringa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

The full error I get on the server console is:

java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
        at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
        at sun.nio.cs.StreamDecoder.read(Unknown Source)
        at java.io.InputStreamReader.read(Unknown Source)
        at java.io.BufferedReader.fill(Unknown Source)
        at java.io.BufferedReader.readLine(Unknown Source)
        at java.io.BufferedReader.readLine(Unknown Source)
        at serverstringa.ThreadStringa.run(ThreadStringa.java:27)

Solution

  • Instead of PrintWriter in client program, you should use DataOutputStream to communicate with Server in socket programming. Also remember to perform close() from client side. I have only modified your client program, you can check this.

    import java.net.*;
    import java.io.*;
    import java.util.Random;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class ClientStringa {
    
        public static void main(String[] args) {
            try{
                Socket socket = new Socket("localhost", 5555);
                DataOutputStream out=new DataOutputStream(socket.getOutputStream());
    //            PrintWriter out = new PrintWriter(socket.getOutputStream());
                Random r = new Random();
                int N = r.nextInt(100);
                for(int i=1;i<=N;i++){
    //                out.println("String" +i);
                    out.writeUTF("String" +i);
                }
                out.flush();
                out.close();
            }
            catch (IOException ex) {
                Logger.getLogger(ClientStringa.class.getName()).log(Level.SEVERE, null, ex);    
            }
        }
    }