2
我在做一个客户端服务器。我已经知道服务器可以发送硬编码文件,但不是指定的客户端。我将不得不发送文本文件。据我了解:客户端首先发送文件名,然后,服务器发送它,没有什么复杂的,但我得到各种错误,这段代码得到一个连接重置/套接字关闭错误。主要的问题是,没有太多时间研究网络。Java请求文件,发送文件(客户端服务器)
我很感激任何帮助,我可以得到。
编辑。 我发现了一个解决办法,关闭一个流导致套接字关闭,为什么?它不应该发生,应该吗?
服务器端:
InputStream sin=newCon.getInputStream();
DataInputStream sdata=new DataInputStream(sin);
location=sdata.readUTF();
//sdata.close();
//sin.close();
File toSend=new File(location);
byte[] array=new byte[(int)toSend.length()];
FileInputStream fromFile=new FileInputStream(toSend);
BufferedInputStream toBuffer=new BufferedInputStream(fromFile);
toBuffer.read(array,0,array.length);
OutputStream out=newCon.getOutputStream(); //Socket-closed...
out.write(array,0,array.length);
out.flush();
toBuffer.close();
newCon.close();
客户方:
int bytesRead;
server=new Socket(host,port);
OutputStream sout=server.getOutputStream();
DataOutputStream sdata=new DataOutputStream(sout);
sdata.writeUTF(interestFile);
//sdata.close();
//sout.close();
InputStream in=server.getInputStream(); //socket closed..
OutputStream out=new FileOutputStream("data.txt");
byte[] buffer=new byte[1024];
while((bytesRead=in.read(buffer))!=-1)
{
out.write(buffer,0,bytesRead);
}
out.close();
server.close();
您在阅读之前是否尝试过使用System.out.println(sdata.available())?也许没有什么可读的。 –
该代码没有运行那么远检查:/ – MustSeeMelons
但它是否到达位置= sdata.readUTF(),你说连接重置?我的意思是在那之前。 –