简体   繁体   中英

Read multiple data from client socket

Code for client which reads data from file and sends to server

public class Step2Client {
    public static void main( String args[ ] ) throws Exception
    {
        String ip="localhost";
        int port=9999;

        Socket s=new Socket(ip,port);
        String line="";
        Scanner scanner=new Scanner(System.in);
        OutputStreamWriter os=new OutputStreamWriter(s.getOutputStream());
        PrintWriter out=new PrintWriter(os);
        FileReader fileReader =new FileReader("input.txt");

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while((line = bufferedReader.readLine()) != null) {
            out.println(line);
            System.out.print(line);
        }
    }
}

Code for server which has print data sent by client line by line:

public class Step2Server {
    public static void main(String args[]) throws Exception
    {
        ServerSocket ss=new ServerSocket(9999);
        Socket s=ss.accept();
        StringBuilder stringBuilder=new StringBuilder();
        InputStreamReader inputStream=new InputStreamReader(s.getInputStream());
        BufferedReader br=new BufferedReader(inputStream);
        String line = null;
        do {
            line = br.readLine ();
            stringBuilder.append(line);
        } while (line != null);
        System.out.print(stringBuilder.toString());
    }
}

But there is following error

Exception in thread "main" java.net.SocketException: Connection reset
at Step2Server.main(Step2Server.java:20)

Your client isn't closing the socket, so when it exits the operating system is resetting it. It must be running on Windows. You should call out.close() after reaching the end of the input file.

NB Your read loop is incorrect. It should be:

while ((line = br.readLine()) != null) {
    stringBuilder.append(line);
}

At present you are appending the final null to the StringBuilder .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM