【发布时间】:2015-11-21 18:46:14
【问题描述】:
感谢您花时间阅读我的问题。
我目前正在开发我的第一个 Android 应用程序。我正在尝试从在 VPS 上不断运行的 Java SocketServer 向 android 应用程序发送一个字符串。当我在 Eclipse 中编写一个 10 行的客户端时,它运行良好。我现在的问题是如何在 Android 中获取响应,因为我收到诸如“您不能在主线程中使用套接字”之类的错误,但我想编写它的方式是使用将响应作为字符串返回的方法。
也许我应该补充一点,我的服务器响应时没有提供输入/字符串。我只想打开连接并从输入流中读取字符串。
我发送的服务器代码:
try {
OutputStream out = socket.getOutputStream();
PrintWriter pw = new PrintWriter(out);
String toSend = "";
//This is just some serialization of own Elements to a string.
boolean first = true;
for (VertretungsPlanElement ele : Main.Elemente) {
if (!first) {
toSend = toSend + "~";
}
first = false;
toSend = toSend + ele.toString();
}
//Serialization ends
pw.println(toSend);
pw.flush();
pw.close();
out.flush();
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
当我尝试从非 Android 客户端获取响应时,此方法有效,但当我尝试在 Android 中获取响应时,它给了我 null 或 ""。
我的安卓代码:
try {
client = new Socket(hostname, port);
BufferedReader is = new BufferedReader(new InputStreamReader(client.getInputStream()));
response = is.readLine();
Vertretungsplan.Cards.add(new VertretungsplanCard("Response:", response));
} catch (Exception e) {}
我现在做了将近一天的研究,我读到了一些关于“AsynchronousTasks”之类的东西。
如果这个问题已经被问过,我很抱歉。
感谢您的宝贵时间和您的帮助!
【问题讨论】:
-
'诸如“你不能在主线程中使用套接字”之类的错误。事实上你不能。你做了什么来解决这个问题?
-
问得很草率的问题。如果你读到流的末尾,它会给你 null。如果您发送了一个空行,它会给您“”。如果不能同时给你这两样东西。从您接受的答案中可以清楚地看出,您确实遇到了异常,这与 null 或“”无关。 从不忽略 IOExceptions。 '“异步任务”什么的'同样草率。
-
我尝试使用 new Thread().start();使用 Runnable 但当然它不起作用,因为使用 runnable 中的 String 我无法做太多事情。对不起,如果您认为我的问题“草率”。下次我试着问得更好。
标签: java android sockets serversocket