zoukankan      html  css  js  c++  java
  • 多客户端和服务器通信的基本流程:

     1 package com.bwf.tcp_cleint;
     2 
     3 import java.text.SimpleDateFormat;
     4 import java.util.Date;
     5 
     6 import android.os.Build;
     7 import android.os.Bundle;
     8 import android.os.Handler;
     9 import android.os.Message;
    10 import android.app.Activity;
    11 import android.view.Menu;
    12 import android.view.View;
    13 import android.view.View.OnClickListener;
    14 import android.widget.Button;
    15 import android.widget.EditText;
    16 import android.widget.ScrollView;
    17 import android.widget.TextView;
    18 /**
    19  * 多客户端和服务器通信的基本流程:
    20  *         1. 在某个客户端的EditText输入要发送的内容
    21  *         2. 点击Button的时候把要发送的内容通过Handler发送到子线程CleintHandler
    22  *         3. 子线程中的CleintHandler收到MSG之后,把其中的数据通过Socket流写入
    23  *         4. 在Server端会读取到客户端写入的内容
    24  *         5. 在Server中把读取到的数据分别写入所有Socket
    25  *         6. 可以在客户端的子线程中读取到Server发送的信息
    26  *         7. 在子线程中通过UIHandler发消息,通知UI来更新
    27  *         8. 重复上述过程
    28  * */
    29 public class MainActivity extends Activity {
    30     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    31     EditText edt_input;
    32     TextView tv_show;
    33     Button btn_send;
    34     
    35     CleintThread cleintThread;
    36     
    37     // 更新UI上TextView显示
    38     Handler uiHandler;
    39     
    40     // ScrollView
    41     ScrollView scrollView;
    42     @Override
    43     protected void onCreate(Bundle savedInstanceState) {
    44         super.onCreate(savedInstanceState);
    45         setContentView(R.layout.activity_main);
    46         
    47         init();
    48     }
    49 
    50     Build bd = new Build();    
    51     String model;
    52     private void init() {
    53         model = bd.MODEL;
    54         edt_input = (EditText) findViewById(R.id.edt_input);
    55         tv_show = (TextView) findViewById(R.id.tv_show);
    56         scrollView = (ScrollView) findViewById(R.id.scrollView);
    57         
    58         uiHandler = new Handler(){
    59                 public void handleMessage(android.os.Message msg) {
    60                     if(msg.what == 0){
    61                         tv_show.append(msg.obj+"
    ");
    62                         // 滑动到底部
    63                         scrollView.fullScroll(ScrollView.FOCUS_DOWN);
    64                         // 滑动到顶部
    65                         //scrollView.fullScroll(ScrollView.FOCUS_UP);
    66                     }
    67                 };
    68             };
    69         
    70         cleintThread = new CleintThread(uiHandler);
    71         // 启动客户端线程
    72         new Thread(cleintThread).start();
    73     }
    74 
    75     @Override
    76     public boolean onCreateOptionsMenu(Menu menu) {
    77         // Inflate the menu; this adds items to the action bar if it is present.
    78         getMenuInflater().inflate(R.menu.main, menu);
    79         return true;
    80     }
    81 
    82     public void mainClick(View v){
      1 package com.bwf.tcp_cleint;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.IOException;
      5 import java.io.InputStreamReader;
      6 import java.io.OutputStream;
      7 import java.io.UnsupportedEncodingException;
      8 import java.net.Socket;
      9 import java.net.UnknownHostException;
     10 import java.text.SimpleDateFormat;
     11 import java.util.Date;
     12 
     13 import android.os.Build;
     14 import android.os.Handler;
     15 import android.os.Looper;
     16 import android.os.Message;
     17 import android.util.Log;
     18 
     19 public class CleintThread implements Runnable {
     20     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     21 
     22     Handler handler;
     23 
     24     public Handler cleintHandler;
     25 
     26     Socket s;
     27     BufferedReader br;
     28     OutputStream out;
     29 
     30     public CleintThread(Handler handler) {
     31         super();
     32         this.handler = handler;
     33     }
     34 
     35     @Override
     36     public void run() {
     37         try {
     38             s = new Socket("192.168.10.124", 8000);
     39             br = new BufferedReader(new InputStreamReader(s.getInputStream()));
     40 
     41             out = s.getOutputStream();
     42 
     43             // 开启一个线程读取服务器返回的数据
     44             new Thread(new Runnable() {
     45 
     46                 @Override
     47                 public void run() {
     48 
     49                     String data = "";
     50                     try {
     51                         while ((data = br.readLine()) != null) {
     52                             // 读取到服务器返回时,发消息给UI中的Handler更新UI
     53                             Message msg = Message.obtain();
     54                             msg.what = 0;
     55                             msg.obj = data;
     56                             handler.sendMessage(msg);
     57                         }
     58                     } catch (Exception e) {
     59                         // TODO Auto-generated catch block
     60                         e.printStackTrace();
     61                     }
     62                 }
     63             }).start();
     64 
     65             // 准备Looper
     66             Looper.prepare();
     67             // 创建Handler以便接收处理UI端发送来的消息,将其写入Socket流中
     68             cleintHandler = new Handler() {
     69                 @Override
     70                 public void handleMessage(Message msg) {
     71                     if (msg.what == 1) {
     72                         try {
     73                             String name = new Build().MODEL;
     74                             int len = name.length();
     75                             int nameMax = 20;
     76                             if(len < nameMax){
     77                                 for (int i = 0; i < nameMax - len; i++) {
     78                                     name += " ";
     79                                 }
     80                             } else{
     81                                 name = name.substring(0, nameMax);
     82                             }
     83                             
     84                             out.write((name
     85                                     + format.format(new Date(System
     86                                             .currentTimeMillis()))
     87                                     + "
    " + msg.obj+"
    ")
     88                                     .getBytes("utf-8"));
     89                         } catch (Exception e) {
     90                             // TODO Auto-generated catch block
     91                             e.printStackTrace();
     92                         }
     93                     }
     94                 }
     95             };
     96 
     97             // 激活消息队列
     98             Looper.loop();
     99         } catch (Exception e) {
    100             // TODO Auto-generated catch block
    101             Log.d("fanhy", "连接服务器失败。");
    102             e.printStackTrace();
    103         }
    104     }
    105 
    106 }
    
    
    
    83         switch (v.getId()) {
    84         case R.id.btn_send:
    85             Message msg = Message.obtain();
    86             msg.what = 1;
    87             msg.obj = edt_input.getText()+"";
    88             // 将EditText中的输入传递给客户端线程进行发送到服务器
    89             cleintThread.cleintHandler.sendMessage(msg);
    90             // 发送后清空EditText
    91             edt_input.setText("");
    92             break;
    93 
    94         default:
    95             break;
    96         }
    97     }
    98 }
  • 相关阅读:
    bzoj4137[FJOI2015]火星商店问题
    HNOI2019游记
    bzoj4785:[ZJOI2017]树状数组:二维线段树
    快速傅里叶变换(FFT)
    动规大总结
    复习动规(4)
    复习动规(3)
    复习动规(2)
    复习动规(1)
    2019CSP-S游记(真)
  • 原文地址:https://www.cnblogs.com/wangyanhui-joel/p/4945749.html
Copyright © 2011-2022 走看看