天天看點

Android學習筆記(七)之Android socket通信-解決中文亂碼

目前想讓手機用戶端和伺服器保持長連接配接故選擇socket進行通信

首先是建立一個socket伺服器端

[java] 

view

plain

copy

  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.  * TODO 
  20.  * @author cuiran 
  21.  * @version TODO 
  22. public class Main {  
  23.     private static final int PORT = 8090;    
  24.     private List<Socket> mList = new ArrayList<Socket>();    
  25.     private ServerSocket server = null;    
  26.     private ExecutorService mExecutorService = null; //thread pool     
  27.     public static final String bm="utf-8"; //全局定義,以适應系統其他部分  
  28.     public static void main(String[] args) {    
  29.         new Main();    
  30.     }    
  31.     public Main() {    
  32.         try {    
  33.             server = new ServerSocket(PORT);    
  34.             mExecutorService = Executors.newCachedThreadPool();  //create a thread pool     
  35.             System.out.print("server start ...");    
  36.             Socket client = null;    
  37.             while(true) {    
  38.                 client = server.accept();    
  39.                 mList.add(client);    
  40.                 mExecutorService.execute(new Service(client)); //start a new thread to handle the connection     
  41.             }    
  42.         }catch (Exception e) {    
  43.             e.printStackTrace();    
  44.         }    
  45.     class Service implements Runnable {    
  46.             private Socket socket;    
  47.             private BufferedReader in = null;    
  48.             private String msg = "";    
  49.             public Service(Socket socket) {    
  50.                 this.socket = socket;    
  51.                 try {    
  52.                     in = new BufferedReader(new InputStreamReader(socket.getInputStream(),bm));    
  53.                     msg = "user" +this.socket.getInetAddress() + "come toal:"    
  54.                         +mList.size();    
  55.                     this.sendmsg();    
  56.                 } catch (IOException e) {    
  57.                     e.printStackTrace();    
  58.                 }    
  59.             @Override    
  60.             public void run() {    
  61.                 // TODO Auto-generated method stub     
  62.                     while(true) {    
  63.                         if((msg = in.readLine())!= null) {    
  64.                             if(msg.equals("exit")) {    
  65.                                 System.out.println("ssssssss");    
  66.                                 mList.remove(socket);    
  67.                                 in.close();    
  68.                                 msg = "user:" + socket.getInetAddress()    
  69.                                     + "exit total:" + mList.size();    
  70.                                 socket.close();    
  71.                                 this.sendmsg();    
  72.                                 break;    
  73.                             } else {    
  74.                                 System.out.println("msg="+msg);  
  75.                                 msg = socket.getInetAddress() + ":" + msg;    
  76.                             }    
  77.                         }    
  78.                     }    
  79.                 } catch (Exception e) {    
  80.            public void sendmsg() {    
  81.                System.out.println(msg);    
  82.                int num =mList.size();    
  83.                for (int index = 0; index < num; index ++) {    
  84.                    Socket mSocket = mList.get(index);    
  85.                    PrintWriter pout = null;    
  86.                    try {    
  87.                        pout = new PrintWriter(new BufferedWriter(    
  88.                                new OutputStreamWriter(mSocket.getOutputStream(),bm)),true);    
  89.                        pout.println(msg);    
  90.                    }catch (IOException e) {    
  91.                        e.printStackTrace();    
  92.                    }    
  93.                }    
  94.            }    
  95.         }   
  96. }  

然後是建立一個android工程:

在檔案【AndroidManifest.xml】添加内容:

[html] 

  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.     <uses-sdk android:minSdkVersion="8" />  
  7.     <uses-permission android:name="android.permission.INTERNET" />  
  8.     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
  9.     <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>  
  10.     <application  
  11.         android:icon="@drawable/ic_launcher"  
  12.         android:label="@string/app_name" >  
  13.         <activity  
  14.             android:name=".SocketActivity"  
  15.             android:label="@string/app_name" >  
  16.             <intent-filter>  
  17.                 <action android:name="android.intent.action.MAIN" />  
  18.                 <category android:name="android.intent.category.LAUNCHER" />  
  19.             </intent-filter>  
  20.         </activity>  
  21.     </application>  
  22. </manifest>  

然後是建立類:

  1. package com.cayden.socket;  
  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.io.UnsupportedEncodingException;  
  9. import java.net.Socket;  
  10. import com.cayden.util.Conf;  
  11. import android.app.Activity;  
  12. import android.app.AlertDialog;  
  13. import android.content.DialogInterface;  
  14. import android.os.Bundle;  
  15. import android.os.Handler;  
  16. import android.os.Message;  
  17. import android.util.Log;  
  18. import android.view.View;  
  19. import android.widget.Button;  
  20. import android.widget.EditText;  
  21. import android.widget.TextView;  
  22. public class SocketActivity extends Activity implements Runnable {  
  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 = "219.143.49.189";    
  28.     private static final int PORT = 8403;    
  29.     private Socket socket = null;    
  30.     private BufferedReader in = null;    
  31.     private PrintWriter out = null;    
  32.     private String content = "";    
  33.     /** Called when the activity is first created. */  
  34.     @Override  
  35.     public void onCreate(Bundle savedInstanceState) {  
  36.         super.onCreate(savedInstanceState);  
  37.         setContentView(R.layout.main);  
  38.         tv_msg = (TextView) findViewById(R.id.TextView);    
  39.         ed_msg = (EditText) findViewById(R.id.EditText01);    
  40. //        btn_login = (Button) findViewById(R.id.Button01);     
  41.         btn_send = (Button) findViewById(R.id.sendBtn);    
  42.             socket = new Socket(HOST, PORT);    
  43.             in = new BufferedReader(new InputStreamReader(socket.getInputStream()));    
  44.             out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(    
  45.                     socket.getOutputStream(),bm)), true);  
  46.             Log.i(Conf.TAG, "連接配接成功");  
  47.         } catch (IOException ex) {    
  48.             ex.printStackTrace();   
  49.             Log.i(Conf.TAG, "出現異常:"+ex.getMessage());  
  50.             ShowDialog("login exception" + ex.getMessage());    
  51.         btn_send.setOnClickListener(new Button.OnClickListener() {    
  52.             public void onClick(View v) {    
  53.                 String msg = ed_msg.getText().toString();    
  54.                 if (socket.isConnected()) {    
  55.                     if (!socket.isOutputShutdown()) {    
  56.                         try {  
  57.                             out.println(msg);  
  58.                         } catch (Exception e) {  
  59.                             e.printStackTrace();  
  60.         });    
  61.         new Thread(SocketActivity.this).start();    
  62.     }  
  63.     public void ShowDialog(String msg) {    
  64.         new AlertDialog.Builder(this).setTitle("notification").setMessage(msg)    
  65.                 .setPositiveButton("ok", new DialogInterface.OnClickListener() {    
  66.                     @Override    
  67.                     public void onClick(DialogInterface dialog, int which) {    
  68.                 }).show();    
  69.     public void run() {  
  70.         // TODO Auto-generated method stub  
  71.             while (true) {    
  72.                     if (!socket.isInputShutdown()) {    
  73.                         if ((content = in.readLine()) != null) {    
  74.                             content += "\n";    
  75.                             mHandler.sendMessage(mHandler.obtainMessage());    
  76.                         } else {    
  77.         } catch (Exception e) {    
  78.      public Handler mHandler = new Handler() {    
  79.             public void handleMessage(Message msg) {    
  80.                 super.handleMessage(msg);    
  81.                 tv_msg.setText(tv_msg.getText().toString() + content);    
  82.         };    
  83. }  

繼續閱讀