1.服务器程序:
Java代码
  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. *comServer
  16. *
  17. *@authorAina.huangE-mail:674023920@qq.com
  18. *@version创建时间:2010Jul14,201010:45:35AM类说明
  19. */
  20. public class Main{
  21. private static final int PORT= 9999 ; //端口监听
  22. private List<Socket>mList= new ArrayList<Socket>(); //存放客户端socket
  23. private ServerSocketserver= null ;
  24. private ExecutorServicemExecutorService= null ; //线程池
  25. /**
  26. *@paramargs
  27. */
  28. public static void main(String[]args){
  29. //TODOAuto-generatedmethodstub
  30. new Main();
  31. }
  32. public Main(){
  33. try {
  34. server= new ServerSocket(PORT);
  35. mExecutorService=Executors.newCachedThreadPool(); //创建一个线程池
  36. System.out.println( "ServerStart..." );
  37. Socketclient= null ;
  38. while ( true ){
  39. client=server.accept();
  40. mList.add(client);
  41. mExecutorService.execute( new Service(client)); //开启一个客户端线程.
  42. }
  43. } catch (Exceptionex){
  44. ex.printStackTrace();
  45. }
  46. }
  47. public class Service implements Runnable{
  48. private Socketsocket;
  49. private BufferedReaderin= null ;
  50. private Stringmsg= "" ;
  51. public Service(Socketsocket){
  52. this .socket=socket;
  53. try {
  54. in= new BufferedReader( new InputStreamReader(socket
  55. .getInputStream()));
  56. msg= "user:" + this .socket.getInetAddress()+ "cometotal:"
  57. +mList.size();
  58. this .sendmsg();
  59. } catch (IOExceptione){
  60. e.printStackTrace();
  61. }
  62. }
  63. public void run(){
  64. //TODOAuto-generatedmethodstub
  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. + "exittotal:" +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 (Exceptionex){
  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. SocketmSocket=mList.get(i);
  96. PrintWriterpout= null ;
  97. try {
  98. pout= new PrintWriter( new BufferedWriter(
  99. new OutputStreamWriter(mSocket.getOutputStream())),
  100. true );
  101. pout.println(msg);
  102. } catch (IOExceptione){
  103. e.printStackTrace();
  104. }
  105. }
  106. }
  107. }
  108. }


2.客户端程序:
添加 android.permission.INTERNET
Java代码
  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. /**Calledwhentheactivityisfirstcreated.*/
  21. private TextViewtv_msg= null ;
  22. private EditTexted_msg= null ;
  23. private Buttonbtn_send= null ;
  24. private Buttonbtn_login= null ;
  25. private static final StringHOST= "192.168.0.132" ;
  26. private static final int PORT= 9999 ;
  27. private Socketsocket= null ;
  28. private BufferedReaderin= null ;
  29. private PrintWriterout= null ;
  30. private Stringcontent= "" ;
  31. @Override
  32. public void onCreate(BundlesavedInstanceState){
  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 (Exceptionex){
  47. ex.printStackTrace();
  48. ShowDialog( "登陆异常:" +ex.getMessage());
  49. }
  50. btn_send.setOnClickListener( new Button.OnClickListener(){
  51. public void onClick(Viewv){
  52. //TODOAuto-generatedmethodstub
  53. Stringmsg=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(Stringmsg){
  64. new AlertDialog.Builder( this ).setTitle( "提示" ).setMessage(msg)
  65. .setPositiveButton( "OK" , new DialogInterface.OnClickListener(){
  66. public void onClick(DialogInterfacedialog, int which){
  67. //TODOAuto-generatedmethodstub
  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. } catch (Exceptionex){
  86. ex.printStackTrace();
  87. }
  88. }
  89. public HandlermHandler= new Handler(){
  90. public void handleMessage(Messagemsg){
  91. super .handleMessage(msg);
  92. Log.i( "TAG" , "--" +msg);
  93. tv_msg.setText(tv_msg.getText().toString()+content);
  94. }
  95. };
  96. }


Java代码
  1. <?xmlversion= "1.0" encoding= "utf-8" ?>
  2. <LinearLayoutxmlns:android= "http://schemas.android.com/apk/res/android"
  3. android:orientation= "vertical" android:layout_width= "fill_parent"
  4. android:layout_height= "fill_parent" >
  5. <TextViewandroid:id= "@+id/TextView" android:singleLine= "false"
  6. android:layout_width= "fill_parent"
  7. android:layout_height= "wrap_content" />
  8. <EditTextandroid:hint= "content" android:id= "@+id/EditText01"
  9. android:layout_width= "fill_parent"
  10. android:layout_height= "wrap_content" >
  11. </EditText>
  12. <Buttonandroid:text= "login" android:id= "@+id/Button01"
  13. android:layout_width= "fill_parent"
  14. android:layout_height= "wrap_content" >
  15. </Button>
  16. <Buttonandroid:text= "send" android:id= "@+id/Button02"
  17. android:layout_width= "fill_parent"
  18. android:layout_height= "wrap_content" >
  19. </Button>
  20. </LinearLayout>

更多相关文章

  1. android亮屏、暗屏、解锁、关闭系统对话的监听事件
  2. SharedPreferences 源码分析
  3. Android中开关按钮IOS效果的实现
  4. Android(安卓)监听网络变化然后刷新页面
  5. Android(安卓)studio爬取网页
  6. Android的线程使用来更新UI----Thread、Handler、Looper、TimerT
  7. eclipse中Android布局的基本操作
  8. Android异步消息处理机制完全解析-Handler详解
  9. Android中Handler Runnable与Thread的区别详解

随机推荐

  1. React Native
  2. Ubuntu 10.04不能连接到HTC G1设备
  3. android webview 缩放及换行
  4. Android读取资源文件夹里的string-array
  5. Android(安卓)Weekly - 第 182 期
  6. RK3288 android7.1.2 android studio 用
  7. android MIME文件类型
  8. android程序入口
  9. Android(安卓)SDK 更新问题
  10. Android获取当前时间的android.text.form