初学Android,网络应用之使用多线程Socket(八十五)

来源:互联网 发布:2017年户外广告数据 编辑:程序博客网 时间:2024/06/05 20:59

接着上一篇,这篇加入多线程的功能,使Socket可以持续连接

服务端 

定义一个线程类

public class ServerThread implements Runnable {// 定义当前线程所处理的SocketSocket s = null;// 该线程所处理的Socket所对应的输入流BufferedReader br = null;public ServerThread(Socket s) throws IOException {this.s = s;// 初始化该Socket对应的输入流br = new BufferedReader(new InputStreamReader(s.getInputStream(),"uft-8"));}@Overridepublic void run() {try{String content = null;    //采用循环不断从Socket中读取客户端发送过来的数据while((content = readFromClient()) != null){//遍历socketList中的每个socket//将读到的内容向每一个socket发送一次for(Socket s : MyServer.socketList){OutputStream os = s.getOutputStream();os.write((content + "\n").getBytes("utf-8"));}}}catch(IOException e){e.printStackTrace();}}//定义读取客户端数据的方法private String readFromClient() {try{return br.readLine();}//如果捕捉到异常,表明该Socket对应的客户端已经关闭catch(IOException e){//删除该SocketMyServer.socketList.remove(s);}return null;}}

服务端调用线程类

public class MyServer {// 定义保存所有Socket的ArrayListpublic static ArrayList<Socket> socketList = new ArrayList<Socket>();public static void main(String[] args) throws IOException{ServerSocket ss = new ServerSocket(34567);while(true){//此行代码会阻塞,将一直等待别人的连接Socket s = ss.accept();socketList.add(s);//每当客户端连接后启动一条ServerThread线程为该客户服务new Thread(new ServerThread(s)).start();}}}

客户端接收是一个Andorid程序

定义一个客户端线程类

public class ClientThread implements Runnable{//该线程负责处理的Socketprivate Socket s;private Handler handler;//该线程所处理的Socket所对应的输入流BufferedReader br = null;public ClientThread(Socket s , Handler handler)throws IOException{this.s = s;this.handler = handler;br = new BufferedReader(new InputStreamReader(s.getInputStream()));}public void run(){try{String content = null;//不断读取Socket输入流中的内容。while ((content = br.readLine()) != null){// 每当读到来自服务器的数据之后,发送消息通知程序界面显示该数据Message msg = new Message();msg.what = 0x123;msg.obj = content;handler.sendMessage(msg);}}catch (Exception e){e.printStackTrace();}}}

Activity中使用线程类

public class MultiThreadClient extends Activity{// 定义界面上的两个文本框EditText input, show;// 定义界面上的一个按钮Button send;OutputStream os;Handler handler;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);input = (EditText) findViewById(R.id.input);send = (Button) findViewById(R.id.send);show = (EditText) findViewById(R.id.show);Socket s;handler = new Handler(){@Overridepublic void handleMessage(Message msg){// 如果消息来自于子线程if (msg.what == 0x123){// 将读取的内容追加显示在文本框中show.append("\n" + msg.obj.toString());}}};try{s = new Socket("10.10.56.243", 34567);// 客户端启动ClientThread线程不断读取来自服务器的数据new Thread(new ClientThread(s, handler)).start(); // ①os = s.getOutputStream();}catch (Exception e){e.printStackTrace();}send.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){try{// 将用户在文本框内输入的内容写入网络os.write((input.getText().toString() + "\r\n").getBytes("utf-8"));// 清空input文本框input.setText("");}catch (Exception e){e.printStackTrace();}}});}}
界面如下




原创粉丝点击