zoukankan      html  css  js  c++  java
  • Socket网络通信例子

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

    服务端程序:

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


    2.客户端程序:
      
    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.   
    9. import android.app.Activity;   
    10. import android.app.AlertDialog;   
    11. import android.content.DialogInterface;   
    12. import android.os.Bundle;   
    13. import android.os.Handler;   
    14. import android.os.Message;   
    15. import android.util.Log;   
    16. import android.view.View;   
    17. import android.widget.Button;   
    18. import android.widget.EditText;   
    19. import android.widget.TextView;   
    20.   
    21. public class Test extends Activity implements Runnable {   
    22.     /** Called when the activity is first created. */  
    23.     private TextView tv_msg = null;   
    24.     private EditText ed_msg = null;   
    25.     private Button btn_send = null;   
    26.     private Button btn_login = null;   
    27.     private static final String HOST = "192.168.0.132";   
    28.     private static final int PORT = 9999;   
    29.     private Socket socket = null;   
    30.     private BufferedReader in = null;   
    31.     private PrintWriter out = null;   
    32.     private String content = "";   
    33.   
    34.     @Override  
    35.     public void onCreate(Bundle savedInstanceState) {   
    36.         super.onCreate(savedInstanceState);   
    37.         setContentView(R.layout.main);   
    38.         tv_msg = (TextView) this.findViewById(R.id.TextView);   
    39.         ed_msg = (EditText) this.findViewById(R.id.EditText01);   
    40.         btn_login = (Button) this.findViewById(R.id.Button01);   
    41.         btn_send = (Button) this.findViewById(R.id.Button02);   
    42.         try {   
    43.             socket = new Socket(HOST, PORT);   
    44.             in = new BufferedReader(new InputStreamReader(socket   
    45.                     .getInputStream()));   
    46.             out = new PrintWriter(new BufferedWriter(   
    47.                     new OutputStreamWriter(socket.getOutputStream())),   
    48.                     true);   
    49.         } catch (Exception ex) {   
    50.             ex.printStackTrace();   
    51.             ShowDialog("登陆异常:" + ex.getMessage());   
    52.         }   
    53.         btn_send.setOnClickListener(new Button.OnClickListener() {   
    54.   
    55.             public void onClick(View v) {   
    56.                 // TODO Auto-generated method stub  
    57.                 String msg = ed_msg.getText().toString();   
    58.                 if (socket.isConnected()) {   
    59.                     if (!socket.isOutputShutdown()) {   
    60.                         out.println(msg);   
    61.                     }   
    62.                 }   
    63.             }   
    64.   
    65.         });   
    66.         new Thread(this).start();   
    67.     }   
    68.   
    69.     public void ShowDialog(String msg) {   
    70.         new AlertDialog.Builder(this).setTitle("提示").setMessage(msg)   
    71.                 .setPositiveButton("OK"new DialogInterface.OnClickListener() {   
    72.   
    73.                     public void onClick(DialogInterface dialog, int which) {   
    74.                         // TODO Auto-generated method stub  
    75.   
    76.                     }   
    77.   
    78.                 }).show();   
    79.     }   
    80.   
    81.     public void run() {   
    82.         try {   
    83.             while (true) {   
    84.                 if(socket.isConnected()){   
    85.                     if(!socket.isInputShutdown()){   
    86.                         if ((content = in.readLine()) != null) {   
    87.                             Log.i("TAG""++ "+content);   
    88.                             content += "\n";   
    89.                             mHandler.sendMessage(mHandler.obtainMessage());   
    90.                         }else{   
    91.                                
    92.                         }   
    93.                     }   
    94.                 }   
    95.                    
    96.             }   
    97.         } catch (Exception ex) {   
    98.             ex.printStackTrace();   
    99.         }   
    100.     }   
    101.   
    102.     public Handler mHandler = new Handler() {   
    103.         public void handleMessage(Message msg) {   
    104.             super.handleMessage(msg);   
    105.             Log.i("TAG""-- "+msg);   
    106.             tv_msg.setText(tv_msg.getText().toString() + content);   
    107.         }   
    108.     };   
    109. }  
  • 相关阅读:
    洛谷P5113 Sabbat of the witch
    「学习笔记」洲阁筛
    【UNR #3】百鸽笼
    LOJ#6703. 小 Q 的序列
    python数组字符串还原为数组
    QGIS导入excel点数据
    QGIS统计面要素中包含的点要素数量
    gpd.read_file(),报错路径在系统文件中不存在
    QGIS平移要素
    QGIS多部件面转单部件面
  • 原文地址:https://www.cnblogs.com/qingblog/p/2607924.html
Copyright © 2011-2022 走看看