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

简介: 目前想让手机客户端和服务器保持长连接故选择socket进行通信 首先是新建一个socket服务器端   [java] view plaincopy /**   * Main.
目前想让手机客户端和服务器保持长连接故选择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.   
  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 plain copy
  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 plain copy
  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. }  
相关文章
|
2月前
|
Python
python socket 简单通信
python socket 简单通信
42 1
|
2月前
|
网络协议 安全 网络安全
网络编程:基于socket的TCP/IP通信。
网络编程:基于socket的TCP/IP通信。
161 0
|
10天前
|
Python
Socket学习笔记(二):python通过socket实现客户端到服务器端的图片传输
使用Python的socket库实现客户端到服务器端的图片传输,包括客户端和服务器端的代码实现,以及传输结果的展示。
67 3
Socket学习笔记(二):python通过socket实现客户端到服务器端的图片传输
|
10天前
|
JSON 数据格式 Python
Socket学习笔记(一):python通过socket实现客户端到服务器端的文件传输
本文介绍了如何使用Python的socket模块实现客户端到服务器端的文件传输,包括客户端发送文件信息和内容,服务器端接收并保存文件的完整过程。
47 1
Socket学习笔记(一):python通过socket实现客户端到服务器端的文件传输
|
5天前
|
网络协议 Linux 应用服务中间件
Socket通信之网络协议基本原理
【10月更文挑战第10天】网络协议定义了机器间通信的标准格式,确保信息准确无损地传输。主要分为两种模型:OSI七层模型与TCP/IP模型。
|
1月前
|
Java Android开发 数据安全/隐私保护
Android中多进程通信有几种方式?需要注意哪些问题?
本文介绍了Android中的多进程通信(IPC),探讨了IPC的重要性及其实现方式,如Intent、Binder、AIDL等,并通过一个使用Binder机制的示例详细说明了其实现过程。
197 4
|
1月前
|
网络协议 Linux 应用服务中间件
Socket通信之网络协议基本原理
【9月更文挑战第14天】网络协议是机器间交流的约定格式,确保信息准确传达。主要模型有OSI七层与TCP/IP模型,通过分层简化复杂网络环境。IP地址全局定位设备,MAC地址则在本地网络中定位。网络分层后,数据包层层封装,经由不同层次协议处理,最终通过Socket系统调用在应用层解析和响应。
|
3月前
|
Java Android开发 Spring
Android Spingboot 实现SSE通信案例
【7月更文挑战第14天】以下是使用Android和Spring Boot实现SSE(Server-Sent Events)通信的案例摘要: 在`MainActivity`中: - 初始化界面元素并设置按钮点击事件。 - `startSseRequest`方法创建`WebClient`对象,设置请求头,发送请求,并处理响应和错误。 请确保将`your-server-url`替换为实际的服务器地址。
96 14
|
2月前
|
Android开发
Android项目架构设计问题之C与B通信如何解决
Android项目架构设计问题之C与B通信如何解决
14 0
|
2月前
|
移动开发 前端开发 weex
Android项目架构设计问题之模块化后调用式通信如何解决
Android项目架构设计问题之模块化后调用式通信如何解决
14 0