服务器/客户端java.net.SocketException

服务器/客户端java.net.SocketException,java,Java,我正在尝试构建一个发送文件的客户机/服务器应用程序,但是我遇到了一个较大文件的问题。我使用BufferedInputStream从文件中读取信息,并使用OutputStream写入套接字。我有一个循环,从文件中读取1KB,然后发送它,这对于前25个循环很好,然后由于套接字写入错误而崩溃。有什么想法吗?这是密码 客户 import java.io.*; import java.net.Socket; import java.util.logging.Level; import java.util.

我正在尝试构建一个发送文件的客户机/服务器应用程序,但是我遇到了一个较大文件的问题。我使用BufferedInputStream从文件中读取信息,并使用OutputStream写入套接字。我有一个循环,从文件中读取1KB,然后发送它,这对于前25个循环很好,然后由于套接字写入错误而崩溃。有什么想法吗?这是密码

客户

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

public class TCPClient
{
public static void main(String[] args)
{
    /*Variables*/
    int serverPort = 8899;
    String ip = "localhost";
    File myFile = new File("GeneratedFile.txt"); //fileToBeSent.txt

    System.out.println(myFile.length());

    try
    {
        /*Connect to Server*/
        Socket sock = new Socket(ip, serverPort);
        System.out.println("Connection Made");

        /*Create Streams*/
        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream clientOutput = sock.getOutputStream();

        /*This is the old code for transfer*/
        /*Create Byte Array
        byte[] myByteArray = new byte[(int) myFile.length()];  //was 1024

        /*Send File
        bis.read(myByteArray, 0, 1024);
        clientOutput.write(myByteArray, 0, 1024);
        clientOutput.flush();
        */

        for(long i = 0; i <= myFile.length(); i += 1024)
        {
            byte[] myByteArray = new byte[1024];
            bis.read(myByteArray, 0, 1024);
            clientOutput.write(myByteArray, 0, 1024);
            clientOutput.flush();
            System.out.println("i is: " + i);
        }
        System.out.println("File Written");
        sock.close();
    } catch (IOException ex)
    {
        Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("You can't do that!");
    }
    System.out.println("Finished");
}
}

你的复制技术不正确。以下是如何在Java中复制流:

byte[] buffer = new byte[8192]; // or whatever you like, but declare it outside the loop
int count;
while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}
out.flush();
// then in a finally block ...
out.close();
in.close();

两端都需要这个。您不能假设任何给定的读取都将填充缓冲区,因此必须循环到EOS。请注意,您不会在循环内刷新

确切的错误是什么?什么是堆栈跟踪?堆栈跟踪很好,但也可以尝试将“clientOutput”输出流包装到BufferedOutputStream中。崩溃发生在客户端还是服务器端?您正在传输的文件有多大?(我的假设是,您的缓冲区对于文件的最后一部分来说太大了)
byte[] buffer = new byte[8192]; // or whatever you like, but declare it outside the loop
int count;
while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}
out.flush();
// then in a finally block ...
out.close();
in.close();