socket和HTTP在Android中的连接请求问题

前阵子的只能小灯的创新实验课上,需要使用Android客户端连接智能小灯实现交互,就用上了socket,一开始对socket并不是很了解,就按照正常的流程进行创建和使用socket,后来发现socket创建时会使APP闪退。后来发现socket不能再主线程中创建,会导致线程堵塞甚至导致APP崩溃,查找网络的资料才发现socket和HTTP一样,在主线程中不能创建,需要创建一个子线程去执行创建socket或者HTTP的操作。
示例如下 :

public class ServerThread implements Runnable {
 2     Socket s = null;
 3     BufferedReader br = null;
 4 
 5     public ServerThread(Socket s) throws IOException {
 6         this.s = s;
 7         br = new BufferedReader(new InputStreamReader(s.getInputStream(),
 8                 "utf-8"));
 9     }
10 
11     public void run() {   //子线程中对socket进行创建
12         try {
13             String content = null;
14             while ((content = readFromClient()) != null) {
15                 for (Iterator<Socket> it = MyServer.socketList.iterator(); it
16                         .hasNext();) {
17                     Socket s = it.next();
18                     try {
19                         OutputStream os = s.getOutputStream();
20                         os.write((content + "\n").getBytes("utf-8"));
21                     } catch (SocketException e) {
22                         e.printStackTrace();
23                         it.remove();
24                         System.out.println(MyServer.socketList);
25                     }
26                 }
27             }
28         } catch (IOException e) {
29             e.printStackTrace();
30         }
31     }
32 
33     private String readFromClient() {
34         try {
35             return br.readLine();
36         } catch (IOException e) {
37             e.printStackTrace();
38             // MyServer.socketList.remove(s);
39             MyServer.socketList.remove(s);
40         }
41         return null;
42     }
43
44 }

同样的socket创建以后,需要进行通信,就有数据的传输,读写文件流字节流也需要在子线程中完成。

猜你喜欢

转载自blog.csdn.net/cqx13763055264/article/details/79146102
今日推荐