gpt4 book ai didi

Java通过套接字发送文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:56:46 24 4
gpt4 key购买 nike

我想通过套接字发送文件以及一些其他信息。我正在使用以下代码

 public void receiveFile(Socket socket,int filesize,String filename) throws IOException
{
//after receiving file send ack
System.out.println("waiting ");
// int filesize=70; // filesize temporary hardcoded

long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
System.out.println("Connecting...");

// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
System.out.println("recv..."+mybytearray.length);
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
System.out.println(bytesRead);
if(bytesRead > 0) current += bytesRead;
} while(bytesRead > 0);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
System.out.println(" File received");
}

接收到文件后,还要接收一些其他的字符串。但是当我尝试读取输入流时,我得到了文件的内容。如何从输入流中刷新文件的内容。

BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(
webServerSocket.getInputStream()));

receiveFile(webServerSocket,filesize,filename);
while(true)
{
msg = inFromServer.readLine(); //here i receive the contents of the file again
System.out.println(msg);
}

最佳答案

将套接字的输入流传递给接收文件方法,而不是套接字本身:

InputStream is = webServerSocket.getInputStream();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(is));

receiveFile(webServerSocket,filesize,filename);

我认为,问题在于您在同一时间点(在实际读取任何数据之前)从同一个套接字创建了两个输入流。它们指向同一个流,但从一个流中读取也不会移动另一个流,因此在从 inputstreamBA 读取后,一个被标记在位置 15(例如),而 inpustream A 仍在位置 0,在流的开头。

(编辑:)当然,您必须在 receiveFile 方法中使用输入流,而不是从套接字中获取输入流。另一种解决方案是在调用接收文件后从套接字获取输入流,如

receiveFile(webServerSocket,filesize,filename);

BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(webServerSocket.getInputStream()));

关于Java通过套接字发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5636001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com