java - Android 应用程序未从 Socket 输入流中读取
问题描述
由于某种原因,我的 android 应用程序没有从我的服务器接收任何数据。奇怪的是,我编写的一个不同的套接字客户端(它在我的计算机上运行,而不是在 AVD 上运行)接收并打印所有服务器发送的消息而没有错误。它使用与方法中包含的代码类似的代码doInBackground
。
public class Client extends AsyncTask<Void, Void, Void> {
int port;
Socket s;
@Override
protected Void doInBackground(Void... voids) {
try {
port = 1818;
s = new Socket("xx.xx.xx.xx", port);
if (!s.isConnected()) {
s.close();
}
BufferedReader re = new BufferedReader(new InputStreamReader(s.getInputStream()));
String temp = null;
while ((temp = re.readLine()) != null)
{
MainActivity.changeT(temp); // This will replace the TextView's text with temp.
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
我在想一个可能的解决方案是将while循环放入一个单独的线程中,但我不确定。欢迎任何建议!:-)
解决方案
当应用程序正确地访问服务器时,MainActivity.changeT(temp);
正在尝试从后台线程访问 UI 线程,这是不合适的。
我通过将 MainActivity 的一个实例传递给这个 Client 类来解决这个问题,并且我使用了runnable
方法runOnUiThread(...)
。
public class Client extends AsyncTask<Void, Void, Void> {
int port;
Socket s;
MainActivity instance;
Client(MainActivity instance)
{
this.instance = instance;
}
@Override
protected Void doInBackground(Void... voids) {
try {
port = 1818;
s = new Socket("xx.xx.xx.xx", port);
if (!s.isConnected()) {
s.close();
return null;
}
BufferedReader re = new BufferedReader(new InputStreamReader(s.getInputStream()));
String temp = null;
TextView t = instance.getT(); // Accesses a getter method that returns the TextView.
while ((temp = re.readLine()) != null)
{
setText(t, temp); // Accesses the UI Thread and changes the TextView.
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
private void setText(final TextView text,final String value){
instance.runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText(value); // This is equivalent to writing the code in the UI thread itself.
}
});
}
推荐阅读
- python - 如何根据一组预设的可接受值检查列表中每个项目的值
- javascript - Javascript – 动态创建的元素上的事件委托不起作用
- swift - 为什么我的 ObservedObject 已更新但未在视图中显示其更新的内容
- java - 无法使用不同的作业名称和组运行同一类,同时运行
- python - 如何在 Python 中关闭 Discord 机器人的日志记录?
- flutter - Flutter - 索引 0、1 和 2 的节点的 Firebase RTDB 读取问题
- c - 分段错误(核心转储) - argv - c
- progressive-web-apps - 更改 Blazor 离线镀铬窗口样式
- node.js - Node.js - 监控每个进程的网络使用情况
- flutter - FutureBuilder with Provider: List 不是 Future 类型的子类型