从客户端套接字读取多个数据

时间:2017-05-10 20:39:59

标签: java sockets tcp java-io

从文件读取数据并发送到服务器的客户端代码

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);
        }
    }
}

服务器代码,其中包含客户端逐行发送的打印数据:

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());
    }
}

但是有以下错误

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

1 个答案:

答案 0 :(得分:0)

您的客户端没有关闭套接字,因此当它退出时,操作系统正在重置它。它必须在Windows上运行。您应该在到达输入文件的末尾后调用out.close()

注意您的读取循环不正确。它应该是:

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

目前,您要将最终null追加到StringBuilder