• android socket通信


    一、创建服务器的步骤

          1、指定端口实例化一个ServerSocket

               ServerSocket severSocket = new ServerSocket(54321);

          2、调用ServerSocket的accept()开始监听客户端的连接,并取得客户端的Socket对象client

               Socket client = severSocket.accept();

          3、获取位于底层Socket的流,以进行读写操作

               //接受客户端的消息
                InputStream is = client.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader in = new BufferedReader(isr);     
                String str =  in.readLine();  

            //向客户端发送消息
                OutputStream os = client.getOutputStream();
                OutputStreamWriter osr = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osr);
                PrintWriter out = new PrintWriter(bw,true);
                out.println("server message");
             

             4、关闭打开的流(注意:先关闭Writer,后关闭Reader)

               in.close();
               out.close();

    二、创建客户端的步骤

          1、通过服务器的IP地址和端口实例化一个Socket,请求连接服务器

               socket = new Socket("ipdizhi",54321);

          2、获取Socket上的流进行读写操作,把流包装进BufferedReader/PrintWriter的实例;并对socket进行读写

          3、关闭流 

    三、网络通信中的乱码问题

    原因:通信过程中使用了不同的编码方式:服务器中的、传输过程中的,终端设备的

    办法:getBytes("编码方式");//对汉字进行重编码,得到它的字节数组

            new String(Bytes[],"解码方式");//对字节数组进行相应的编码

    实例:1、将流先转换为字节,再将字节按GB2312的方式转换得到字符串

             InputStream is = con.getInputStream();

             BufferedInputStream bis= new BufferedInputStream(is));

             byte a[] = new byte[1024];

             int currrent = -1;

             int i=0;

             while((currrent= bis.read())!=-1){

                 byte a[i] = (byte)current;

                 i++;

             }

             result = new String(a,"GB2312");

              2、在数据传递过程中使用ISO-8859-1字符集,在传递到终端设备时,将数据反转

              public static String FormotStr(String str){

                  if(str==null||str=="") return "";

                  try{

                         return new String(str.getBytes("ISO-8859-1"),"bgk");

                   }catch (UnsupportedEncodingException e){

                         return str;

                   }

              }

     以下附代码实例

    Client
     1 public class Client extends Activity{
     2     private TextView mTextView = null;
     3     private EditText mEditText = null;
     4     private Button mButton = null;
     5     
     6     @Override
     7     public void onCreate(Bundle savedInstanceState) {
     8         super.onCreate(savedInstanceState);
     9         setContentView(R.layout.socket);
    10         
    11         mTextView = (TextView)findViewById(R.id.textView1);  
    12         mEditText = (EditText)findViewById(R.id.editText1);  
    13         mButton = (Button)findViewById(R.id.button1);  
    14         
    15         mButton.setOnClickListener(new OnClickListener() {
    16             
    17             @Override
    18             public void onClick(View v) {
    19                 Socket socket = null;
    20                 String str = mEditText.getText().toString();
    21                 try{
    22                     socket = new Socket("ipdizhi",54321);
    23                     //向服务器发送消息
    24                     OutputStream os = socket.getOutputStream();
    25                     OutputStreamWriter osr = new OutputStreamWriter(os);
    26                     BufferedWriter bw = new BufferedWriter(osr);
    27                     PrintWriter out = new PrintWriter(bw,true);
    28                     out.println(str);
    29                     
    30                     //接收来自服务器的消息
    31                     InputStream is = socket.getInputStream();
    32                     InputStreamReader isr = new InputStreamReader(is);
    33                     BufferedReader br = new BufferedReader(isr);
    34                     String msg = br.readLine();
    35                     if(msg!=null){
    36                         mTextView.setText(msg);
    37                     }else
    38                         mTextView.setText("数据错误");
    39                     
    40                     out.close();
    41                     br.close();
    42                     socket.close();                                                        
    43                 }catch(Exception e){
    44                     Log.e("socket",e.getMessage()+"close");
    45                     e.printStackTrace();
    46                 }
    47                 
    48             }
    49         }); 
    50     }
    51 
    52 }
    Server
     1 public  class Server implements Runnable{
     2 
     3     @Override
     4     public void run() {
     5         System.out.println("run");
     6         try{
     7             ServerSocket severSocket = new ServerSocket(54321);
     8             System.out.println("severSocket");
     9             while(true){
    10                 System.out.println("true");
    11                 //接收客户端请求
    12                 Socket client = severSocket.accept();
    13                 System.out.println("accept");
    14                 try{
    15                     //接受客户端消息
    16                     InputStream is = client.getInputStream();
    17                     InputStreamReader isr = new InputStreamReader(is);
    18                     BufferedReader in = new BufferedReader(isr);
    19                     
    20                     String str = in.readLine();                                        
    21                     System.out.println("read:"+str);
    22                     
    23                     /*System.out.println("请在键盘上输入你想输入的内容,输完后按回车结束:");
    24                     Scanner inn=new Scanner(System.in);
    25                     String strr=inn.next();
    26                     System.out.println("您刚才在键盘输入的信息是:"+strr);*/
    27 
    28                     
    29                     //向客户端发送消息
    30                     OutputStream os = client.getOutputStream();
    31                     OutputStreamWriter osr = new OutputStreamWriter(os);
    32                     BufferedWriter bw = new BufferedWriter(osr);
    33                     PrintWriter out = new PrintWriter(bw,true);
    34                     //解决中文乱码
    35                     String strrr = "此处写服务器想发送给客户端的消";
    36                     byte a[] = new byte[1024];
    37                     a = strrr.getBytes(strrr);
    38                     String strend = new String(a,"gb2312");
    39 
    40                     out.println(strend);
    41                     
    42                     //关闭流
    43                     in.close();
    44                     out.close();    
    45                 }catch(Exception e){
    46                     System.out.println(e.getMessage());
    47                     System.out.println("222");
    48                     e.printStackTrace();
    49                 }
    50                 finally{
    51                     client.close();
    52                     System.out.println("close");
    53                 }
    54             }
    55         }catch(Exception e){
    56             System.out.println(e.getMessage());
    57             System.out.println("333");
    58         }
    59     }
    60 //main函数,开启服务器
    61     public static void main(String a[]){
    62         Thread deskTopServerThread = new Thread(new Server());
    63         deskTopServerThread.start();                
    64     }
    65 }
  • 相关阅读:
    前端git开发分支各种场景管理
    RxJS Subject学习
    微信小程序登陆流程(20200322)
    vue依赖收集的策略
    eggjs2.x版本异步获取config配置方案
    dubbo连接过程
    计算机中对流的理解
    Egg.js运行环境配置场景
    Promise和Observable的映射
    eggjs异常捕获机制
  • 原文地址:https://www.cnblogs.com/wyqfighting/p/2695186.html
Copyright © 2020-2023  润新知