多客户端和服务器通信的基本流程
1. Java代码
另附TCP与udp的区别
package com.bwf.tcp_cleint; import java.text.SimpleDateFormat; import java.util.Date; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ScrollView; import android.widget.TextView; /** * 多客户端和服务器通信的基本流程: * 1. 在某个客户端的EditText输入要发送的内容 * 2. 点击Button的时候把要发送的内容通过Handler发送到子线程CleintHandler * 3. 子线程中的CleintHandler收到MSG之后,把其中的数据通过Socket流写入 * 4. 在Server端会读取到客户端写入的内容 * 5. 在Server中把读取到的数据分别写入所有Socket * 6. 可以在客户端的子线程中读取到Server发送的信息 * 7. 在子线程中通过UIHandler发消息,通知UI来更新 * 8. 重复上述过程 * */ public class MainActivity extends Activity { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); EditText edt_input; TextView tv_show; Button btn_send; CleintThread cleintThread; // 更新UI上TextView显示 Handler uiHandler; // ScrollView ScrollView scrollView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } Build bd = new Build(); String model; private void init() { model = bd.MODEL; edt_input = (EditText) findViewById(R.id.edt_input); tv_show = (TextView) findViewById(R.id.tv_show); scrollView = (ScrollView) findViewById(R.id.scrollView); uiHandler = new Handler(){ public void handleMessage(android.os.Message msg) { if(msg.what == 0){ tv_show.append(msg.obj+"\n"); // 滑动到底部 scrollView.fullScroll(ScrollView.FOCUS_DOWN); // 滑动到顶部 //scrollView.fullScroll(ScrollView.FOCUS_UP); } }; }; cleintThread = new CleintThread(uiHandler); // 启动客户端线程 new Thread(cleintThread).start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public void mainClick(View v){ switch (v.getId()) { case R.id.btn_send: Message msg = Message.obtain(); msg.what = 1; msg.obj = edt_input.getText()+""; // 将EditText中的输入传递给客户端线程进行发送到服务器 cleintThread.cleintHandler.sendMessage(msg); // 发送后清空EditText edt_input.setText(""); break; default: break; } } }
2
package com.bwf.tcp_cleint; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Date; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; public class CleintThread implements Runnable { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Handler handler; public Handler cleintHandler; Socket s; BufferedReader br; OutputStream out; public CleintThread(Handler handler) { super(); this.handler = handler; } @Override public void run() { try { s = new Socket("192.168.10.124", 8000); br = new BufferedReader(new InputStreamReader(s.getInputStream())); out = s.getOutputStream(); // 开启一个线程读取服务器返回的数据 new Thread(new Runnable() { @Override public void run() { String data = ""; try { while ((data = br.readLine()) != null) { // 读取到服务器返回时,发消息给UI中的Handler更新UI Message msg = Message.obtain(); msg.what = 0; msg.obj = data; handler.sendMessage(msg); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); // 准备Looper Looper.prepare(); // 创建Handler以便接收处理UI端发送来的消息,将其写入Socket流中 cleintHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { try { String name = new Build().MODEL; int len = name.length(); int nameMax = 20; if(len < nameMax){ for (int i = 0; i < nameMax - len; i++) { name += " "; } } else{ name = name.substring(0, nameMax); } out.write((name + format.format(new Date(System .currentTimeMillis())) + "\r\n" + msg.obj+"\n") .getBytes("utf-8")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; // 激活消息队列 Looper.loop(); } catch (Exception e) { // TODO Auto-generated catch block Log.d("fanhy", "连接服务器失败。"); e.printStackTrace(); } } }