java - 提高简单 TCP 客户端/套接字上的数据传输速度

标签 java sockets tcp stream

我的家庭作业是通过重定向标准 I/O,使用客户端/服务器 TCP 套接字对创建一个简单的数据传输机制。我实际上让它工作,但是当我尝试传输大文件(比如 ~5g)时,速度会急剧下降。我正在使用 BufferedInputStream 和 BufferedOutputStream,我认为也许我可以在那里进行一些优化。我的服务器的代码是:

private static final int BUF_SIZE = 2047;

public static void main(String[] args) throws IOException{
   /*
    * Attempt to parse command line arguments.
    * @require args[0] is an int
    */
   int port = 0;
   try {
       port = Integer.parseInt(args[0]);
   } catch(NumberFormatException e) {
       System.err.println("Port must be an integer in range 0 - 65535.");
       System.exit(-1);
   }

   /*
    * Bind server socket to specified port number and wait for request.
    * @require port >= 0 && port <= 65535
    */
   ServerSocket welcomeSocket = null;
   welcomeSocket = new ServerSocket(port);
   System.out.println("Now listening on port: " + port);

    /*
     * Accept connection from client socket.
     */
    Socket connectionSocket = null;
    connectionSocket = welcomeSocket.accept();
    System.out.println("Client made connection");

    BufferedInputStream input;
    BufferedOutputStream output;
    if(System.in.available() > 0) {
        input = new BufferedInputStream(System.in, BUF_SIZE);
        output = new BufferedOutputStream(
                connectionSocket.getOutputStream(), BUF_SIZE);
    } else {
        input = new BufferedInputStream(
                connectionSocket.getInputStream(), BUF_SIZE);
        output = new BufferedOutputStream(System.out, BUF_SIZE);
    }

    int place;
    while((place = input.read()) != -1)
        output.write(place);

    input.close();
    output.close();
    welcomeSocket.close();
    connectionSocket.close();
}

客户端代码本质上是一样的。我曾尝试使用不同的缓冲区大小,包括默认值(通过不指定缓冲区大小),但它们都以大致相同的速度运行。关于如何提高我的表现的任何指示?

感谢您的宝贵时间!

最佳答案

while((place = input.read()) != -1)

您一次从缓冲区中读取一个字节。调用此方法数百万次的开销相当大。

我建议使用另一个版本将一个以上的字节读入缓冲区(并以相同的方式写入):

public int read(byte[] b,
            int off,
            int len)

例子:

byte[] myBuffer = new byte[BUF_SIZE];
while((place = input.read(myBuffer, 0, BUF_SIZE)) != 1)
    output.write(myBuffer, 0, place);

关于java - 提高简单 TCP 客户端/套接字上的数据传输速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7411135/

相关文章:

c# - 如何以编程方式查找特定服务正在监听的端口

c++ - 使用 IOCP 的 TCP/IP 服务器。接收缓冲区中的偶尔数据损坏

java - Java 中 JSON 未知的字符串

java - 如何中断网页的加载?

java - 了解 Playframework 示例项目中的 AsyncController

java - 方法匹配效果不佳

java - 在java中使用socket填充html表单

c++ - 使用 C++/boost 套接字的简单客户端/服务器在 Windows 下工作,但在 Linux 下失败

Java Sockets - 在没有输入流的情况下检测网络断开连接

sockets - 为什么我不应该在端口 80 上运行我的非 Web 服务器软件?