Android和PC上的流套接字应用程序

时间:2013-01-05 10:23:48

标签: android sockets

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

1 个答案:

答案 0 :(得分: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();
 }

希望它也适合你。