• Android之socket多线程


    一、添加权限

    <uses-permission android:name="android.permission.INTERNET" />
    

    二、输入输出流

    客户端和服务器端的输入输出流的问题容易搞混淆:如下图

    在客户端:

    socket.getInputStream();从socket读来自服务器的数据

    socket.getOutputStream();向socket中写数据,传给服务器,服务器在它的socket的输入流读这个数据

    在服务器端:

    socket.getInputStream();从socket读来自客户端的数据

    socket.getOutputStream();向socket中写数据,传给客户端,客户端在它的socket的输入流读这个数据

    就是说客户端和服务器端的输入输出流是对应的,输入流连接到输出流 

    输入输出流的包装:

    方法一:数据二进制流

    DataInputStream in=new DataInputStream(socket.getInputStream());//接收客户端信息
    DataOutputStream out=new DataOutputStream(socket.getOutputStream());  //向客户端发送消息
    

    方法二:

    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    三、客户端/服务器端实现

    创建服务器端的步骤
    1,指定端口实例化一个ServerSocket

    2,调用ServerSocket的accept方法等待连接期间阻塞

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

    4,将数据封装成流

    5,对Socket进行读写

    6,关闭流

    创建客户端的步骤:

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

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

    3,将数据封装成流(BufferedReader/PrintWriter,DataOutputStream/DataInputStream)的实例

    4,对Socket进行读写

    5,关闭流

    socketClient,java

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.Socket;
     
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
     
    public class socketClient extends Activity {
        private Button button;
        private TextView text;
        private EditText edit;
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            button = (Button) findViewById(R.id.button);
            edit = (EditText) findViewById(R.id.edit);
            text = (TextView) findViewById(R.id.text);
     
            button.setOnClickListener(new View.OnClickListener() {
                private Socket socket = null;
     
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
     
                    String sendMsg = edit.getText().toString() + "
    ";
     
                    try {
                        socket = new Socket("192.168.0.37", 8888); // 创建Socket,其中ip地址为我的PC机器的地址,手机通过wifi上网和服务器在一个网段
     
                        // PrintWriter out = new PrintWriter(new BufferedWriter(new
                        // OutputStreamWriter(socket.getOutputStream())),true);
                        // out.println(sendMsg);
                        //                  
                        // BufferedReader in = new BufferedReader(new
                        // InputStreamReader(socket.getInputStream()));
                        // String readMsg = in.readLine();
                        // if(readMsg !=null){
                        // text.setText(readMsg);
                        // }else{
                        // text.setText("错误");
                        // }
                        //                  
                        // out.close();
                        // in.close();
                        // socket.close();
     
                        DataOutputStream out = new DataOutputStream(socket
                                .getOutputStream()); // 向服务器发送消息
                        out.writeUTF(sendMsg);
                        out.flush();
     
                        DataInputStream in = new DataInputStream(socket
                                .getInputStream()); // 接收来自服务器的消息
                        String readMsg = in.readUTF();
                        if (readMsg != null) {
                            text.setText(readMsg);
                        }
                        out.close();
                        in.close();
                        socket.close();
     
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    

    Server.java

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
     
    public class Server {
        public Server(){
            new ServerThread().start();
        }
        class ServerThread extends Thread{
            public void run() {
                try {
                    ServerSocket ss=new ServerSocket(8888); ////创建一个ServerSocket对象,并让这个ServerSocket在8888端口监听
                    while(true){
                        Socket socket=ss.accept(); //调用ServerSocket的accept()方法,接受客户端所发送的请求,如果客户端没有发送数据,那么该线程就停滞不继续
    //                  try {
    //                      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));  //接收客户端信息
    //                      String readline = in.readLine();
    //                      System.out.println("readline:"+readline);
    //                      
    //                      PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
    //                      out.println("link server success");
    //                      
    //                      in.close();   //关闭流
    //                      out.close();//关闭流
    //                      socket.close();//关闭打开的socket
    //                      
    //                  } catch (Exception e) {
    //                      // TODO: handle exception
    //                  }finally{
    //                  //  socket.close();//
    //                  }
                        try {
                            DataInputStream in=new DataInputStream(socket.getInputStream());//接收客户端信息
                            String readline=in.readUTF();
                            System.out.println(readline);
                                 
                            DataOutputStream out=new DataOutputStream(socket.getOutputStream());  //向客户端发送消息
                            out.writeUTF("link server success");
                            out.flush();
                             
                            in.close();   //关闭流
                            out.close();//关闭流
                            socket.close();//关闭打开的socket
                             
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        }
                    }
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
        public static void main(String[] args) throws IOException {
            new Server();   //开启服务器
        }
         
     
    }
    

      

      

  • 相关阅读:
    magento 去掉index.php
    TCP三次握手与四次挥手
    <Jper和Iperf>的安装及使用
    【Python】安装方法小结
    【ubuntu】日常网络配置信息的查看及修改
    DNS解析
    【Dig工具】
    【ping/tracert】的简单使用
    【VMvare】yum在线源
    配置文件加载
  • 原文地址:https://www.cnblogs.com/eniac1946/p/7597732.html
Copyright © 2020-2023  润新知