【发布时间】:2017-10-27 22:49:50
【问题描述】:
我一直在这方面花费了很多时间,但似乎无法解决。我是自学成才,对此不是很熟悉,所以如果这是一个补救问题,请原谅我。我正在将数据从 Android 发送到 .Net 服务器。数据在编码时越来越损坏,我知道我只是不知道如何修复。我正在使用此处找到的 .Net Async 服务器示例代码:Microsoft Async Sample
我的安卓客户端代码是:
try {
final Socket sock = new Socket();
final int timeOut = (int) TimeUnit.SECONDS.toMillis(5); // 5 sec wait period
sock.connect(new InetSocketAddress("localhost", 11000), timeOut);
if (sock.isConnected()==true){
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
String FileName = "myfile.jpg";
StringBuilder hd = new StringBuilder();
try {
String FilePath= Environment.getExternalStorageDirectory() + "/mydir/" + FileName;
File file = new File(FilePath);
FileInputStream is = new FileInputStream(file);
byte[] chunk = new byte[40960];
int chunkLen = 0;
while ((chunkLen = is.read(chunk)) != -1) {
//String str = new String(Base64.encodeToString(chunk, Base64.NO_WRAP));
//String str = new String(chunk, "ASCII");
String str = new String(chunk, "UTF-8");
out.write(str);
}
//out.write(hd.toString());
} catch (FileNotFoundException fnfE) {
// file not found, handle case
} catch (IOException ioE) {
// problem reading, handle case
}
out.write("<EOF>");
out.flush();
StringBuilder returnString = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
returnString.append(line).append('\n');
}
out.close();
in.close();
sock.close();
}else{
sock.close();
}
} catch (IOException e) {
e.printStackTrace();
}
正如您在我的 cmets 中看到的,我尝试过 base64 和 UTF-8。当我这样做时,我在服务器上遇到各种错误。如果我使用 Base64,我不会得到 Base64 错误的一部分(额外填充等)。 UTF8 写入文件但它已损坏。当我将其全部作为一个 Base64 字符串发送时,它可以正常工作,因为我使用“Dim data As Byte() = Convert.FromBase64String(FileData)”,但正如预期的那样,它会在 Android 中为大文件引发内存错误,从而导致分块。我正在发送一些纯 ASCII 文本,因此我解析出非 ASCII 内容以写入文件。我超级卡住了,任何帮助将不胜感激。提前致谢。
【问题讨论】:
标签: android sockets encoding utf-8