Android asynctask 从套接字读取
我在读取/写入 TCP 服务器时遇到一些问题,我正在为其构建应用程序。在最近的一个帖子中,有人建议我使用服务,但这是一个学校项目,建议使用 asyncTask,所以我也可以这样做。
所以我得到的类是我的活动类和异步类,活动中没有发生任何有趣的事情,只是发送一个正在工作的字符串,所以我无法继续使用异步类。
class ServerTask extends AsyncTask<Void, Void, Void>{
public static String ip = "10.0.2.2";
public static int port = 2002;
Socket socket;
public DataInputStream dis;
public DataOutputStream dos;
public String message;
@Override
protected Void doInBackground(Void... params) {
try {
socket = new Socket(ip, port);
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
} catch (Exception e) {
Log.i("AsyncTank", "Cannot create Socket");
}
while(socket.isConnected()){
read();
}
}
}
return null;
}
public void write(String message) {
try {
if (socket.isConnected()){
dos.writeUTF(message);
dos.flush();
} else {
Log.i("AsynkTask", "Socket appears to be closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "Writing failed");
}
}
public String read() {
try {
if (socket.isConnected()) {
message = dis.readLine();
} else {
Log.i("AsyncTask", "Cannot read");
}
} catch (Exception e) {
Log.i("AsyncTask", "Cannot read from stream");
}
return message;
}
}
我所知道的事情是,服务器确实收到了消息,但直到我重新启动服务器后它才会更新,这让我相信我没有推送新行或使其在关闭后全部显示为一行的东西。然而,这也可能是我不负责的服务器,所以我必须阅读其中的内容。
然而,读取部分不想工作,我不确定如何调用该方法以使其不断侦听服务器套接字并对服务器作出反应?我尝试在 doInBackGround 返回之前创建一个线程,但随后应用程序开始工作几秒钟,由于内存不足而强制关闭?我需要一个线程来持续监听吗?
正如您可能猜到的那样,整个要点是进行聊天,因此 read 方法最终应该更新我的活动类中的 textView。发送方法正在“工作”,但并不像它应该的那样,尽管这可能就像我之前所说的服务器在做一些时髦的业务。
另一个问题是,是否可以像我一样将读取作为一种方法,或者当服务器发送数据然后调用该方法时是否必须做出反应?
编辑 我现在已经将读取部分或至少其中一些移动到了 doInBackGround,所以现在
dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
message = dis.readLine();
Log.i("AsynkTask", "Read : "+message+" this is doInBackGround!");
这加上在服务器中简单地硬编码打印行的更改使我在客户端中读取了该行,所以我猜它现在工作得很好。
看起来怎么样?这段代码完全是垃圾吗?应该以其他方式完成吗?得到了我的功能,但可以这么说,学习做得更好也不错:)。
Im having some trouble reading/writing to a tcp server for which im building an app. In a recent thread I was suggested to use a service instead but this is a project for school which suggested asyncTask so I might aswell go for that.
So the classes ive got are my activity class and async, nothing interesting is going on in activity but sending a string which is working so ill get on with the async one.
class ServerTask extends AsyncTask<Void, Void, Void>{
public static String ip = "10.0.2.2";
public static int port = 2002;
Socket socket;
public DataInputStream dis;
public DataOutputStream dos;
public String message;
@Override
protected Void doInBackground(Void... params) {
try {
socket = new Socket(ip, port);
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
} catch (Exception e) {
Log.i("AsyncTank", "Cannot create Socket");
}
while(socket.isConnected()){
read();
}
}
}
return null;
}
public void write(String message) {
try {
if (socket.isConnected()){
dos.writeUTF(message);
dos.flush();
} else {
Log.i("AsynkTask", "Socket appears to be closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "Writing failed");
}
}
public String read() {
try {
if (socket.isConnected()) {
message = dis.readLine();
} else {
Log.i("AsyncTask", "Cannot read");
}
} catch (Exception e) {
Log.i("AsyncTask", "Cannot read from stream");
}
return message;
}
}
Things I do know, the server DOES get the messages but it doesnt update until I restart the server which leads me to believe that im not pushing a new line or something which makes it all appear as one line after its closed. This however might aswell be the server for which im not reponsible so ill have to read up in that.
The read part however does not want to work, im not sure on how to call the method to have it constantly listen and react to the servers sockt? I tried make a thread just before the return in doInBackGround but then the application starts works for a couple of seconds the force closes due to lack of memory? Do I need a thread to keep constantly listen?
The whole point of this as you might guess is to make a chat so the read method is eventually supposed to update a textView in my activity class. The send method is "working" but not as it should though this might be as I said earlier the server doing some funky buisness.
Another one, is it even possible to have the read as a method like I have or does something have to react when the server sends data and then call the method?
Edit
I have now moved the read part, or atleast some of it to doInBackGround so its now
dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
message = dis.readLine();
Log.i("AsynkTask", "Read : "+message+" this is doInBackGround!");
This along with a change to simply hardcode a printline in the server made me read that line in the client so im guessing its working realtively good for now.
How is it looking? Is it utter crap this code and should be done some other way? Got my functionality but never bad to learn to do it better so to speak :).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在 AsyncTask 的 doInBackground() 方法中对 Socket 进行写入和读取操作,因为两者都需要时间并且可能会阻塞主 (UI) 线程。我不知道你如何调用上面的 write() 方法,但你可能还想看看这个 可能相关的问题。
You should do both your writing and reading to the Socket in an AsyncTask's doInBackground() method, as both take time and could block the main (UI) thread. I don't know how you are calling your write() method above but you might also want to take a look at this question that might be related.