0

我需要构建一个应用程序来将文件从 PC 发送到 Android 智能手机。在 PC 端,我使用 C# 程序读取文件并通过流套接字发送它,在 Android 端我必须构建一个程序来接收文件作为流。所以任何人都可以帮助我或给出一个简单的一步一步的流套接字应用程序。

4

1 回答 1

0

之前我正在使用它来读取通过 IOS 和 Mac 的套接字发送的流,所以我想它也应该对你有用:

        ServerSocket serverSocket = null;
        Socket client = null;
        try {
            serverSocket = new ServerSocket(5000); // port number which the server will use to send the stream
            Log.d("","CREATE SERVER SOCKET");
        } catch (IOException e) {
             e.printStackTrace();
        }
        try {
            if(serverSocket!=null){
                client = serverSocket.accept();
                client.setKeepAlive(true);
                client.setSoTimeout(10000);
                InputStream is = client.getInputStream();

                Log.w("READ","is Size : "+is.available());

                byte[] bytes = DNSUtils.readBytes(is);

            }
        } catch (IOException e) {
                e.printStackTrace();
        }

这就是您实际读取发送字节的方式:

  public static byte[] readBytes(InputStream inputStream) throws IOException {
     // this dynamically extends to take the bytes you read
     ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

     // this is storage overwritten on each iteration with bytes
     int bufferSize = 1024;
     byte[] buffer = new byte[bufferSize];

     // we need to know how may bytes were read to write them to the byteBuffer
     int len = 0;
     while ((len = inputStream.read(buffer)) != -1) {
       byteBuffer.write(buffer, 0, len);
     }

     // and then we can return your byte array.
     return byteBuffer.toByteArray();
 }

希望它也对你有用。

于 2013-01-05T12:05:15.990 回答