• Android socket编程


          Socket通常也称做”套接字“,用于描述IP地址和端口,它就是网络通信过程中端点的抽象表示。Java在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。

    • SocketServer类,服务器实现:
    public class SocketServer {
         
         ServerSocket sever;
         
         public SocketServer(int port){
             try{
                 sever = new ServerSocket(port);
             }catch(IOException e){
                 e.printStackTrace();
             }
         }
         
         public void beginListen(){
             while(true){
                 try{
                     final Socket socket = sever.accept();
                     
                     new Thread(new Runnable(){
                         public void run(){
                             BufferedReader in;
                             try{
                                 in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
                                 PrintWriter out = new PrintWriter(socket.getOutputStream());
                                 while (!socket.isClosed()){
                                     String str;
                                     str = in.readLine();
                                     out.println("Hello!world!! " + str);
                                     out.flush();
                                     if (str == null || str.equals("end"))
                                         break;
                                     System.out.println(str);
                                 }
                                 socket.close();
                             }catch(IOException e){
                                 e.printStackTrace();
                             }
                         }
                     }).start();
                 }catch(IOException e){
                     e.printStackTrace();
                 }
             }
         }
     }
    public class TestSocketServer {
         
         public static void main(String[] argvs){
             SocketServer server = new SocketServer(12345);
             server.beginListen();
         }
     }

    客户端实现:
    public class SocketClientDemo extends Activity implements Runnable {
        private TextView tv_msg = null;
        private EditText ed_msg = null;
        private Button btn_send = null;
        private static final String HOST = "192.168.1.223";
        private static final int PORT = 12345;
        private Socket socket = null;
        private BufferedReader in = null;
        private PrintWriter out = null;
        private String content = "";
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            tv_msg = (TextView) findViewById(R.id.TextView);
            ed_msg = (EditText) findViewById(R.id.EditText01);
            btn_send = (Button) findViewById(R.id.Button01);
    
            try {
                socket = new Socket(HOST, PORT);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                        socket.getOutputStream())), true);
            } catch (IOException ex) {
                ex.printStackTrace();
                ShowDialog("login exception" + ex.getMessage());
            }
            btn_send.setOnClickListener(new Button.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    String msg = ed_msg.getText().toString();
                    if (socket.isConnected()) {
                        if (!socket.isOutputShutdown()) {
                            out.println(msg);
                        }
                    }
                }
            });
            new Thread(SocketDemo.this).start();
        }
    
        public void run() {
            try {
                while (true) {
                    if (socket.isConnected()) {
                        if (!socket.isInputShutdown()) {
                            if ((content = in.readLine()) != null) {
                                content += "\n";
                                Log.d("socket","socket:"+content);
                            } else {
    
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    

    注意在AndroidManifest.xml中加入对网络的访问权限

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




  • 相关阅读:
    2.6.2.MySQL主从复制的原理
    2.4.5 MySQL InnoDB重做与回滚介绍
    PRML读书笔记_绪论曲线拟合部分
    python3_字符串
    PRML读书笔记_绪论
    python3_列表、元组、集合、字典
    linux_软件安装
    shell获取帮助
    linux_查看磁盘与目录容量
    linux_压缩解压命令(zip/tar)
  • 原文地址:https://www.cnblogs.com/xyzlmn/p/3168077.html
Copyright © 2020-2023  润新知