Android4chodison

android天地,爱好android,加油!与大家共同进步!

Android基于客户端和服务器的Socket编程例子之Socket基础通讯--socket模型使用
服务器端:
  1. package com;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStreamWriter;
  7. import java.io.PrintWriter;
  8. import java.net.ServerSocket;
  9. import java.net.Socket;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.concurrent.ExecutorService;
  13. import java.util.concurrent.Executors;
  14. /**
  15. * com Server
  16. *
  17. * @author Aina.huang E-mail: 674023920@qq.com
  18. * @version 创建时间:2010 Jul 14, 2010 10:45:35 AM 类说明
  19. */
  20. public class Main {
  21. private static final int PORT = 9999;// 端口监听
  22. private List<Socket> mList = new ArrayList<Socket>();// 存放客户端socket
  23. private ServerSocket server = null;
  24. private ExecutorService mExecutorService = null;// 线程池
  25. /**
  26.   * @param args
  27.   */
  28. public static void main(String[] args) {
  29.   // TODO Auto-generated method stub
  30.   new Main();
  31. }
  32. public Main() {
  33.   try {
  34.    server = new ServerSocket(PORT);
  35.    mExecutorService = Executors.newCachedThreadPool();// 创建一个线程池
  36.    System.out.println("Server Start...");
  37.    Socket client = null;
  38.    while (true) {
  39.     client = server.accept();
  40.     mList.add(client);
  41.     mExecutorService.execute(new Service(client));// 开启一个客户端线程.
  42.    }
  43.   } catch (Exception ex) {
  44.    ex.printStackTrace();
  45.   }
  46. }
  47. public class Service implements Runnable {
  48.   private Socket socket;
  49.   private BufferedReader in = null;
  50.   private String msg = "";
  51.   public Service(Socket socket) {
  52.    this.socket = socket;
  53.    try {
  54.     in = new BufferedReader(new InputStreamReader(socket
  55.       .getInputStream()));
  56.     msg = "user:" + this.socket.getInetAddress() + " come total:"
  57.       + mList.size();
  58.     this.sendmsg();
  59.    } catch (IOException e) {
  60.     e.printStackTrace();
  61.    }
  62.   }
  63.   public void run() {
  64.    // TODO Auto-generated method stub
  65.    try {
  66.     while (true) {
  67.      if ((msg = in.readLine()) != null) {
  68.       if (msg.equals("exit")) {
  69.        System.out.println("sssssssssss");
  70.        mList.remove(socket);
  71.        in.close();
  72.        msg = "user:" + socket.getInetAddress()
  73.          + " exit total:" + mList.size();
  74.        socket.close();
  75.        this.sendmsg();
  76.        break;
  77.       } else {
  78.        msg = socket.getInetAddress() + " : " + msg;
  79.        this.sendmsg();
  80.       }
  81.      }
  82.     }
  83.    } catch (Exception ex) {
  84.     System.out.println("server 读取数据异常");
  85.     ex.printStackTrace();
  86.    }
  87.   }
  88.   /**
  89.    * 发送消息给所有客户端
  90.    */
  91.   public void sendmsg() {
  92.    System.out.println(msg);
  93.    int num = mList.size();
  94.    for (int i = 0; i < num; i++) {
  95.     Socket mSocket = mList.get(i);
  96.     PrintWriter pout = null;
  97.     try {
  98.      pout = new PrintWriter(new BufferedWriter(
  99.        new OutputStreamWriter(mSocket.getOutputStream())),
  100.        true);
  101.      pout.println(msg);
  102.     } catch (IOException e) {
  103.      e.printStackTrace();
  104.     }
  105.    }
  106.   }
  107. }
  108. }



接下来是客服端程序:
  1. package com.Aina.Android;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStreamWriter;
  6. import java.io.PrintWriter;
  7. import java.net.Socket;
  8. import android.app.Activity;
  9. import android.app.AlertDialog;
  10. import android.content.DialogInterface;
  11. import android.os.Bundle;
  12. import android.os.Handler;
  13. import android.os.Message;
  14. import android.util.Log;
  15. import android.view.View;
  16. import android.widget.Button;
  17. import android.widget.EditText;
  18. import android.widget.TextView;
  19. public class Test extends Activity implements Runnable {
  20. /** Called when the activity is first created. */
  21. private TextView tv_msg = null;
  22. private EditText ed_msg = null;
  23. private Button btn_send = null;
  24. private Button btn_login = null;
  25. private static final String HOST = "192.168.0.132";
  26. private static final int PORT = 9999;
  27. private Socket socket = null;
  28. private BufferedReader in = null;
  29. private PrintWriter out = null;
  30. private String content = "";
  31. @Override
  32. public void onCreate(Bundle savedInstanceState) {
  33.   super.onCreate(savedInstanceState);
  34.   setContentView(R.layout.main);
  35.   tv_msg = (TextView) this.findViewById(R.id.TextView);
  36.   ed_msg = (EditText) this.findViewById(R.id.EditText01);
  37.   btn_login = (Button) this.findViewById(R.id.Button01);
  38.   btn_send = (Button) this.findViewById(R.id.Button02);
  39.   try {
  40.    socket = new Socket(HOST, PORT);
  41.    in = new BufferedReader(new InputStreamReader(socket
  42.      .getInputStream()));
  43.    out = new PrintWriter(new BufferedWriter(
  44.      new OutputStreamWriter(socket.getOutputStream())),
  45.      true);
  46.   } catch (Exception ex) {
  47.    ex.printStackTrace();
  48.    ShowDialog("登陆异常:" + ex.getMessage());
  49.   }
  50.   btn_send.setOnClickListener(new Button.OnClickListener() {
  51.    public void onClick(View v) {
  52.     // TODO Auto-generated method stub
  53.     String msg = ed_msg.getText().toString();
  54.     if (socket.isConnected()) {
  55.      if (!socket.isOutputShutdown()) {
  56.       out.println(msg);
  57.      }
  58.     }
  59.    }
  60.   });
  61.   new Thread(this).start();
  62. }
  63. public void ShowDialog(String msg) {
  64.   new AlertDialog.Builder(this).setTitle("提示").setMessage(msg)
  65.     .setPositiveButton("OK", new DialogInterface.OnClickListener() {
  66.      public void onClick(DialogInterface dialog, int which) {
  67.       // TODO Auto-generated method stub
  68.      }
  69.     }).show();
  70. }
  71. public void run() {
  72.   try {
  73.    while (true) {
  74.     if(socket.isConnected()){
  75.      if(!socket.isInputShutdown()){
  76.       if ((content = in.readLine()) != null) {
  77.        Log.i("TAG", "++ "+content);
  78.        content += "\n";
  79.        mHandler.sendMessage(mHandler.obtainMessage());
  80.       }else{
  81.       
  82.       }
  83.      }
  84.     }
  85.     
  86.    }
  87.   } catch (Exception ex) {
  88.    ex.printStackTrace();
  89.   }
  90. }
  91. public Handler mHandler = new Handler() {
  92.   public void handleMessage(Message msg) {
  93.    super.handleMessage(msg);
  94.    Log.i("TAG", "-- "+msg);
  95.    tv_msg.setText(tv_msg.getText().toString() + content);
  96.   }
  97. };
  98. }


接下来是XML文件布局。
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical" android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <TextView android:id="@+id/TextView" android:singleLine="false"
  6.   android:layout_width="fill_parent"
  7.   android:layout_height="wrap_content" />
  8. <EditText android:hint="content" android:id="@+id/EditText01"
  9.   android:layout_width="fill_parent"
  10.   android:layout_height="wrap_content">
  11. </EditText>
  12. <Button android:text="login" android:id="@+id/Button01"
  13.   android:layout_width="fill_parent"
  14.   android:layout_height="wrap_content">
  15. </Button>
  16. <Button android:text="send" android:id="@+id/Button02"
  17.   android:layout_width="fill_parent"
  18.   android:layout_height="wrap_content">
  19. </Button>
  20. </LinearLayout> 
阅读更多
个人分类: android-Socket
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Android基于客户端和服务器的Socket编程例子之Socket基础通讯--socket模型使用

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭