在java中使用数据报从客户端向服务器发送视频/音频?

时间:2009-11-18 02:50:47

标签: java udp datagram

大家好,我对UDP和Datagrams有点问题。我应该创建一个服务器,它将从客户端获取请求在同一目录中发送文件。然后,UDP服务器将获取此文件(视频),将其放入数据报并发送。我想我知道怎么做,但我不能把文件放在数据报中。我把它放在二进制形式,所以记住这一点。

到目前为止,这是我的代码: 编辑:顺便说一句,这是服务器,我一直遇到BufferedInputReader和OutputReader的问题,所以请记住:)

   Scanner inFromUser = new Scanner(System.in);
    int port = 12345;
    DatagramSocket server = new DatagramSocket(port);
  // Read name of file supplied by client (must be a line of text):
    Scanner in = new Scanner(new DataInputStream(server.getInputStream()));
    String filename = in.nextLine();
    DatagramSocket request = server.accept();


    // Create buffer, then we're ready to go:
    // Puts file into binary form
        BufferedInputStream inbinary = 
                new BufferedInputStream(new FileInputStream("poop.txt"));
   // Outputs the binary form
        BufferedOutputStream outbinary = 
                new BufferedOutputStream(request.getOutputStream());

    int numbytes;
    int countblocks = 0;
    int countbytes = 0;
    byte[] buf = new byte[1024];
    DatagramPacket packet = new DatagramPacket(buf, buf.length, port);
    server.receive(packet);

    while ((numbytes = inbinary.read(buf,0,1024)) >= 0)
    {
     // receive packet from client, telling it to send the video file
     server.receive(packet);
     InetAddress address = packet.getAddress();
     packet = new DatagramPacket(buf, buf.length, address, port);
     server.send(packet);
     countblocks++;          // keep statistics on file size
     countbytes += numbytes;
     outbinary.write(buf,0,numbytes); // write buffer to socket
    }
      outbinary.flush(); // FLUSH THE BUFFER
      server.close(); // done with the socket
      System.out.println(countblocks + " were read; " + countbytes + " bytes");
    }
  }

1 个答案:

答案 0 :(得分:2)

我暂时还没有完成数据报,但我很确定accept()调用是错误的。这是针对TCP服务器的。

我建议使用Sun的优秀教程:http://java.sun.com/docs/books/tutorial/networking/datagrams/clientServer.html