Android-Socket多线程应用(聊天室客户端、Handler的简单使用)
主界面:
- 设置点击按钮后写入output流
- 初始化handler处理获取的input流
- 初始化socket并开启socket线程
- 得到socket的output流引用
void BindEvent() { send.setOnClickListener(new OnClickListener(){ @Override public void onClick(View view) { Toast.makeText(MulteThreadClientActivity.this, "send", Toast.LENGTH_LONG).show(); try{ // 将用户在文本框内输入的内容写入网络 outputStream.write((input.getText().toString() + "\r\n").getBytes("utf-8")); input.setText(""); }catch(Exception e){ e.printStackTrace(); } } }); } void Init() { handler = new Handler(){ @Override public void handleMessage(Message msg) { // 如果发送的消息来自子线程 if(msg.what == 0x123){ // 将读取的内容追加显示在文本框中 show.append("\n" + msg.obj.toString()); } } }; try{ socket = new Socket("192.168.1.154", 30000); // 客户端启动ClientThread线程不断读取来自服务器的数据 new Thread(new ClientThread(socket, handler)).start(); outputStream = socket.getOutputStream(); }catch(Exception e){ e.printStackTrace(); } }
线程中:
- 构造函数中,得到socket的bufferedreader
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- run函数里监听bufferedreader.readLine()是否有新内容传过来
public class ClientThread implements Runnable { // 该线程负责处理的Socket private Socket socket; private Handler handler; // 该线程所处理的Socket所对应的输入流 private BufferedReader bufferedReader = null; public ClientThread(Socket socket, Handler handler) throws IOException{ this.socket = socket; this.handler = handler; bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); } @Override public void run() { try{ String content = null; // 不断读取Socket输入流中的内容 while((content = bufferedReader.readLine()) != null){ // 每当读取到来自服务器的数据后,发送消息通知程序界面显示该数据 Message msg = new Message(); msg.what = 0x123; msg.obj = content; handler.sendMessage(msg); } }catch(Exception e){ e.printStackTrace(); } } }
一个人无梦想,同条咸鱼有咩分别?!