android的socket发送数据格式,Android通过socket发送大文件

目前我正在尝试为我的

Android设备创建一个小套接字应用程序.

我想通过套接字连接将大文件(~500MB)发送到我的笔记本电脑/ PC或其他任何东西.我在我的Android设备上使用套接字客户端连接到我的PC上的套接字服务器但是,当我尝试发送测试字段(~460MB)时,我的应用程序崩溃了,它说:

“Throwing OutOfMemoryError “Failed to allocate a 441616290 byte

allocationwith 4194304 free bytes and 90MB until OOM””

我想我的客户端无法处理这个文件大小.所以我的问题是:有没有办法用TCP套接字连接处理这些大文件?我的代码可以很好地处理小文件(例如5MB),但是它会因较大的文件而失败.

这是我到目前为止:

客户端在我的Android设备上运行:

private class Connecting extends AsyncTask

{

@Override

protected String doInBackground(String... serverAdd)

{

String filePath = "Path to file";

File sdFile = new File(filePath);

try {

client = new Socket("ip", "port");

outputStream = client.getOutputStream();

byte[] buffer = new byte[1024];

FileInputStream in = new FileInputStream(sdFile);

int rBytes;

while((rBytes = in.read(buffer, 0, 1024)) != -1)

{

outputStream.write(buffer, 0, rBytes);

}

outputStream.flush();

outputStream.close();

client.close();

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

}

服务器端:

public class Main {

private static ServerSocket serverSocket;

private static Socket clientSocket;

private static InputStream inputStream;

private static FileOutputStream fileOutputStream;

private static BufferedOutputStream bufferedOutputStream;

private static int filesize = 10000000;

private static int bytesRead;

private static int current = 0;

public static void main(String[] args) throws IOException {

serverSocket = new ServerSocket(10898);

System.out.println("Server started. Listening to the port 10898");

clientSocket = serverSocket.accept();

byte[] mybytearray = new byte[filesize];

inputStream = clientSocket.getInputStream();

fileOutputStream = new FileOutputStream("E:\\output.zip");

bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

System.out.println("Receiving...");

bytesRead = inputStream.read(mybytearray, 0, mybytearray.length);

current = bytesRead;

do {

bytesRead = inputStream.read(mybytearray, current, (mybytearray.length - current));

if (bytesRead >= 0) {

current += bytesRead;

}

} while (bytesRead > -1);

bufferedOutputStream.write(mybytearray, 0, current);

bufferedOutputStream.flush();

bufferedOutputStream.close();

inputStream.close();

clientSocket.close();

serverSocket.close();

System.out.println("Sever recieved the file");

}

}

格尔茨

[编辑]:客户端代码.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值