作者eliang ()
看板java
标题[问题] 用 socket 传输档案
时间Wed May 17 21:30:45 2006
Hi, 我试着写一个可以传档案的小程式,
原始码在本文最下方,
程序很简单, 基本上就是 server 等待 client 的连线,
连线之後就传一个档案给 client, 然後结束程式,
我用家中两台电脑测试, 近端网路照理说速度可以到 100Mbps,
但结果只有 100 KB/s 左右, 後来我试着增加 buffer size,
最多也只能到 170 KB/s, 请问为什麽速度会这麽慢啊?
非常感谢!!
----------------------------以下程式原始码--------------------------
//---------------------------
// Server.java
//---------------------------
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String[] args) throws IOException
{
// buffer size = 1MB
byte data[] = new byte[1024*1024];
// 传输 "test.zip" 这个档案
FileInputStream fileIn = new FileInputStream("test.zip");
// 使用 port 2345
ServerSocket ss = new ServerSocket(2345);
// 等待连线
Socket s = ss.accept();
OutputStream out = s.getOutputStream();
// 填满整个 buffer (1MB) 之後, 才送出去
int size;
while ((size = fileIn.read(data)) != -1)
{
out.write(data, 0, size);
out.flush();
}
s.close();
}
}
//------------------------------
// Client.java
//------------------------------
package test;
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String[] args)
throws UnknownHostException, IOException
{
// buffer size = 1MB
byte data[] = new byte[1024*1024];
// 连结某个 IP 的 port 2345
Socket s = new Socket("192.168.1.1", 2345);
InputStream in = s.getInputStream();
// 将传过来的档案存成 "test.zip"
FileOutputStream fileOut = new FileOutputStream("test.zip");
long start = System.currentTimeMillis();
// 填满 buffer (1MB) 後, 才把资料写入到档案
int size;
while ((size = in.read(data)) != -1)
{
fileOut.write(data, 0, size);
fileOut.flush();
}
s.close();
fileOut.close();
// 取得档案大小
File file = new File("test.zip");
long fileSize = file.length();
long end = System.currentTimeMillis();
// 计算传输时间 (second) 及速度 (KB/s), 然後印出来
double duration = ((double) end - (double) start) / 1000.0;
double speed = ((double) fileSize / 1024) / duration;
System.out.println("Duration: " + duration + " seconds");
System.out.println("Speed: " + speed + " KB/s");
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.132.133.199
※ 编辑: eliang 来自: 220.132.133.199 (05/17 21:36)