我正在做一个客户端服务器。我已经了解到服务器可以发送硬编码的文件,但不能发送指定的客户端。我将只发送文本文件。据我了解:客户端首先发送文件名,然后服务器发送文件名,没有什么复杂的,但是我遇到了各种各样的错误,此代码正在获得连接重置/套接字关闭错误。主要问题是,没有太多时间来研究网络。
我会很感激我能得到的任何帮助。
编辑。
我找到了解决方法,关闭流会导致套接字关闭,为什么呢?它不应该发生,对吗?
服务器端:
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();
最佳答案
在写入客户端输出流时,请尝试从服务器中分块读取文件,而不是创建临时字节数组并将整个文件读取到内存中。如果请求的文件很大怎么办?还要在finally块中在服务器端关闭新的Socket,以便即使抛出异常也要关闭套接字。
服务器端:
Socket newCon = ss.accept();
FileInputStream is = null;
OutputStream out = null;
try {
InputStream sin = newCon.getInputStream();
DataInputStream sdata = new DataInputStream(sin);
String location = sdata.readUTF();
System.out.println("location=" + location);
File toSend = new File(location);
// TODO: validate file is safe to access here
if (!toSend.exists()) {
System.out.println("File does not exist");
return;
}
is = new FileInputStream(toSend);
out = newCon.getOutputStream();
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = is.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
} finally {
if (out != null)
try {
out.close();
} catch(IOException e) {
}
if (is != null)
try {
is.close();
} catch(IOException e) {
}
newCon.close();
}
如果使用Apache Common IOUtils库,则可以减少许多代码来将文件读/写到流。在这里5线下降到1线。
org.apache.commons.io.IOUtils.copy(is, out);
请注意,拥有通过绝对路径到远程客户端来提供文件的服务器是潜在的危险,并且目标文件应限于给定的目录和/或文件类型集。不想将系统级文件提供给未经身份验证的客户端。