网络传输文件的问题(100分)

  • 主题发起人 windofsun
  • 开始时间
hyzou:
现在又有了问题:从客户端上传时,直接用长度等于文件长度的byte数组缓冲。服务器端接收时,则用1024字节来缓冲,我以为这样可以加快速度。但实际情况是:服务器保存后的文件比客户端上传的文件稍大了点。如果只能一个byte一个byte去读,将来目标客户端B来取数据的时候那不是慢的要死了?
我该如何是好呢:(
// 从客户端上传
// 以流的形式,从文件到Socket
private boolean fileToSocket(String pFileName, Socket pSocket) throws IOException
{
File fileUpload = new File(pFileName);
FileInputStream finUpload = new FileInputStream(fileUpload);
try
{
// 文件长度
int intLength = (int)fileUpload.length();
// 保存到缓冲数组
byte[] buf = new byte[intLength];

OutputStream soutUpload;
soutUpload = pSocket.getOutputStream();

if (finUpload.read(buf) <= 0)
{
System.err.println("读取文件错误!");
return false;
}
soutUpload.flush();

try
{
soutUpload.write(buf);
}
catch (IOException e)
{
return false;
}
}
finally
{
finUpload.close();
}
return true;
}

// 服务器端,从端口接收数据
private void sockToFile(String pFileName, Socket pSocket) throws IOException
{
FileOutputStream foutReceive = new FileOutputStream(pFileName);
try
{
// 每次读取1024字节
byte[] buf = new byte[1024];
InputStream sinReceive;
sinReceive = pSocket.getInputStream();
StringBuffer strBuf = new StringBuffer(1024);

int intReceive;
while (true)
{
intReceive = sinReceive.read(buf, 0, buf.length);
if (intReceive == -1)
break;
strBuf.append(new String(buf, "ISO-8859-1"));
}
System.out.println("length ="+strBuf.toString().length());
System.out.println("length ="+strBuf.toString().trim().length());
foutReceive.write(strBuf.toString().trim().getBytes("ISO-8859-1"));
}
finally
{
foutReceive.close();
}
}
 
intReceive = sinReceive.read(buf, 0, buf.length);
这里不是可以得到接受字串的长度吗?处理一下就可以了
另外1024也太小了,局域网的话用65k吧
 
接收方如何处理才能去掉末尾无用的信息呢?因为向strBuf末尾添加总是把整个buf添加进去。转化成String再trim也没用。
还有,被发送文件可能是任何格式,不能限制文本格式。另外这个东西将来要用于拨号的用户,而不只是局域网。
 
append(new String(buf, 0,intReceive ,"ISO-8859-1"))
你问的问题太细了,这些都应该自己解决的
 
不好意思,我学JAVA没多长时间,所以很多问题都不知道
 
多人接受答案了。
 
顶部