Android学习笔记(七)之Android socket通信-解决中文乱码

目前想让手机客户端和服务器保持长连接故选择socket进行通信

首先是新建一个socket服务器端

 

[java] view plaincopy
  1. /** 
  2.  * Main.java 
  3.  * 版权所有(C) 2012  
  4.  * 创建:cuiran 2012-09-14 08:56:16 
  5.  */  
  6. package com.wpndemo.socket;  
  7. import java.io.BufferedReader;    
  8. import java.io.BufferedWriter;    
  9. import java.io.IOException;    
  10. import java.io.InputStreamReader;    
  11. import java.io.OutputStreamWriter;    
  12. import java.io.PrintWriter;    
  13. import java.net.ServerSocket;    
  14. import java.net.Socket;    
  15. import java.util.ArrayList;    
  16. import java.util.List;    
  17. import java.util.concurrent.ExecutorService;    
  18. import java.util.concurrent.Executors;    
  19.   
  20. /** 
  21.  * TODO 
  22.  * @author cuiran 
  23.  * @version TODO 
  24.  */  
  25. public class Main {  
  26.   
  27.     private static final int PORT = 8090;    
  28.     private List<Socket> mList = new ArrayList<Socket>();    
  29.     private ServerSocket server = null;    
  30.     private ExecutorService mExecutorService = null//thread pool     
  31.     public static final String bm="utf-8"//全局定义,以适应系统其他部分  
  32.   
  33.     public static void main(String[] args) {    
  34.         new Main();    
  35.     }    
  36.     public Main() {    
  37.         try {    
  38.             server = new ServerSocket(PORT);    
  39.             mExecutorService = Executors.newCachedThreadPool();  //create a thread pool     
  40.             System.out.print("server start ...");    
  41.             Socket client = null;    
  42.             while(true) {    
  43.                 client = server.accept();    
  44.                 mList.add(client);    
  45.                 mExecutorService.execute(new Service(client)); //start a new thread to handle the connection     
  46.             }    
  47.         }catch (Exception e) {    
  48.             e.printStackTrace();    
  49.         }    
  50.     }    
  51.     class Service implements Runnable {    
  52.             private Socket socket;    
  53.             private BufferedReader in = null;    
  54.             private String msg = "";    
  55.                 
  56.             public Service(Socket socket) {    
  57.                 this.socket = socket;    
  58.                 try {    
  59.                     in = new BufferedReader(new InputStreamReader(socket.getInputStream(),bm));    
  60.                     msg = "user" +this.socket.getInetAddress() + "come toal:"    
  61.                         +mList.size();    
  62.                     this.sendmsg();    
  63.                 } catch (IOException e) {    
  64.                     e.printStackTrace();    
  65.                 }    
  66.                     
  67.             }    
  68.     
  69.             @Override    
  70.             public void run() {    
  71.                 // TODO Auto-generated method stub     
  72.                 try {    
  73.                     while(true) {    
  74.                         if((msg = in.readLine())!= null) {    
  75.                             if(msg.equals("exit")) {    
  76.                                 System.out.println("ssssssss");    
  77.                                 mList.remove(socket);    
  78.                                 in.close();    
  79.                                 msg = "user:" + socket.getInetAddress()    
  80.                                     + "exit total:" + mList.size();    
  81.                                 socket.close();    
  82.                                 this.sendmsg();    
  83.                                 break;    
  84.                             } else {    
  85.                                 System.out.println("msg="+msg);  
  86.                                 msg = socket.getInetAddress() + ":" + msg;    
  87.                                 this.sendmsg();    
  88.                             }    
  89.                         }    
  90.                     }    
  91.                 } catch (Exception e) {    
  92.                     e.printStackTrace();    
  93.                 }    
  94.             }    
  95.               
  96.            public void sendmsg() {    
  97.                System.out.println(msg);    
  98.                int num =mList.size();    
  99.                for (int index = 0; index < num; index ++) {    
  100.                    Socket mSocket = mList.get(index);    
  101.                    PrintWriter pout = null;    
  102.                    try {    
  103.                        pout = new PrintWriter(new BufferedWriter(    
  104.                                new OutputStreamWriter(mSocket.getOutputStream(),bm)),true);    
  105.                        pout.println(msg);    
  106.                    }catch (IOException e) {    
  107.                        e.printStackTrace();    
  108.                    }    
  109.                }    
  110.            }    
  111.         }   
  112. }  


然后是新建一个android工程:

在文件【AndroidManifest.xml】添加内容:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.cayden.socket"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk android:minSdkVersion="8" />  
  8.     <uses-permission android:name="android.permission.INTERNET" />  
  9.     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
  10.     <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>  
  11.     <application  
  12.         android:icon="@drawable/ic_launcher"  
  13.         android:label="@string/app_name" >  
  14.         <activity  
  15.             android:name=".SocketActivity"  
  16.             android:label="@string/app_name" >  
  17.             <intent-filter>  
  18.                 <action android:name="android.intent.action.MAIN" />  
  19.   
  20.                 <category android:name="android.intent.category.LAUNCHER" />  
  21.             </intent-filter>  
  22.         </activity>  
  23.     </application>  
  24.   
  25. </manifest>  


然后是创建类:

[java] view plaincopy
  1. package com.cayden.socket;  
  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.io.UnsupportedEncodingException;  
  10. import java.net.Socket;  
  11.   
  12. import com.cayden.util.Conf;  
  13.   
  14. import android.app.Activity;  
  15. import android.app.AlertDialog;  
  16. import android.content.DialogInterface;  
  17. import android.os.Bundle;  
  18. import android.os.Handler;  
  19. import android.os.Message;  
  20. import android.util.Log;  
  21. import android.view.View;  
  22. import android.widget.Button;  
  23. import android.widget.EditText;  
  24. import android.widget.TextView;  
  25.   
  26. public class SocketActivity extends Activity implements Runnable {  
  27.       
  28.     private TextView tv_msg = null;    
  29.     private EditText ed_msg = null;    
  30.     private Button btn_send = null;    
  31. //    private Button btn_login = null;     
  32.     private static final String HOST = "219.143.49.189";    
  33.     private static final int PORT = 8403;    
  34.     private Socket socket = null;    
  35.     private BufferedReader in = null;    
  36.     private PrintWriter out = null;    
  37.     private String content = "";    
  38.   
  39.     public static final String bm="utf-8"//全局定义,以适应系统其他部分  
  40.   
  41.   
  42.       
  43.     /** Called when the activity is first created. */  
  44.     @Override  
  45.     public void onCreate(Bundle savedInstanceState) {  
  46.         super.onCreate(savedInstanceState);  
  47.         setContentView(R.layout.main);  
  48.           
  49.         tv_msg = (TextView) findViewById(R.id.TextView);    
  50.         ed_msg = (EditText) findViewById(R.id.EditText01);    
  51. //        btn_login = (Button) findViewById(R.id.Button01);     
  52.         btn_send = (Button) findViewById(R.id.sendBtn);    
  53.     
  54.         try {    
  55.             socket = new Socket(HOST, PORT);    
  56.             in = new BufferedReader(new InputStreamReader(socket.getInputStream()));    
  57.             out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(    
  58.                     socket.getOutputStream(),bm)), true);  
  59.             Log.i(Conf.TAG, "连接成功");  
  60.         } catch (IOException ex) {    
  61.             ex.printStackTrace();   
  62.             Log.i(Conf.TAG, "出现异常:"+ex.getMessage());  
  63.             ShowDialog("login exception" + ex.getMessage());    
  64.         }    
  65.         btn_send.setOnClickListener(new Button.OnClickListener() {    
  66.     
  67.             @Override    
  68.             public void onClick(View v) {    
  69.                 // TODO Auto-generated method stub     
  70.                 String msg = ed_msg.getText().toString();    
  71.                 if (socket.isConnected()) {    
  72.                     if (!socket.isOutputShutdown()) {    
  73.                         try {  
  74.                             out.println(msg);  
  75.                         } catch (Exception e) {  
  76.                           
  77.                             e.printStackTrace();  
  78.                         }    
  79.                     }    
  80.                 }    
  81.             }    
  82.         });    
  83.         new Thread(SocketActivity.this).start();    
  84.   
  85.     }  
  86.       
  87.     public void ShowDialog(String msg) {    
  88.         new AlertDialog.Builder(this).setTitle("notification").setMessage(msg)    
  89.                 .setPositiveButton("ok"new DialogInterface.OnClickListener() {    
  90.     
  91.                     @Override    
  92.                     public void onClick(DialogInterface dialog, int which) {    
  93.                         
  94.     
  95.                     }    
  96.                 }).show();    
  97.     }    
  98.   
  99.   
  100.     @Override  
  101.     public void run() {  
  102.         // TODO Auto-generated method stub  
  103.         try {    
  104.             while (true) {    
  105.                 if (socket.isConnected()) {    
  106.                     if (!socket.isInputShutdown()) {    
  107.                         if ((content = in.readLine()) != null) {    
  108.                             content += "\n";    
  109.                             mHandler.sendMessage(mHandler.obtainMessage());    
  110.                         } else {    
  111.     
  112.                         }    
  113.                     }    
  114.                 }    
  115.             }    
  116.         } catch (Exception e) {    
  117.             e.printStackTrace();    
  118.         }    
  119.   
  120.     }  
  121.      public Handler mHandler = new Handler() {    
  122.             public void handleMessage(Message msg) {    
  123.                 super.handleMessage(msg);    
  124.                 tv_msg.setText(tv_msg.getText().toString() + content);    
  125.             }    
  126.         };    
  127.   
  128. }  
上一篇:windows phone 7,sliverlight 下载网页的解析,关于wp7 gb2312编码


下一篇:运用CRM系统利器,优化企业业务流程