• Android 自定义C/S两用Socket框架


    两用框架

    代码

    public class mSocket {
        private ServerSocket connection;
        private Socket socket;
        private ObjectOutputStream output;
        private ObjectInputStream input;
        private int port,backlog;
        private String ip;
    
        public mSocket() {
        }
    
        public mSocket(int port, int backlog) {
            this.port = port;
            this.backlog = backlog;
            runServer();
        }
    
        public mSocket(String ip,int port) {
            this.port = port;
            this.ip = ip;
        }
    
        private void runServer() {
            try {
                connection = new ServerSocket(port ,backlog);
                socket = connection.accept();
                output = new ObjectOutputStream(socket.getOutputStream());
                input = new ObjectInputStream(socket.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public boolean buildConnection() {
            try {
                socket = new Socket(InetAddress.getByName(ip), 8848);
                input = new ObjectInputStream(socket.getInputStream());
                output = new ObjectOutputStream(socket.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
    
    
        public String getMessage() {
            String s = "";
            try {
                s = input.readObject() + "";
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
            return s;
        }
    
        public void sendMessage(final Object object) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        output.writeObject(object);
                        output.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    
        public String getIPAddress(Context context) {
            NetworkInfo info = ((ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                    try {
                        //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                            NetworkInterface intf = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                                InetAddress inetAddress = enumIpAddr.nextElement();
                                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                    return inetAddress.getHostAddress();
                                }
                            }
                        }
                    } catch (SocketException e) {
                        e.printStackTrace();
                    }
    
                } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                    return ipAddress;
                }
            } else {
                //当前无网络连接,请在设置中打开网络
            }
            return null;
        }
    
        private static String intIP2StringIP(int ip) {
            return (ip & 0xFF) + "." +
                    ((ip >> 8) & 0xFF) + "." +
                    ((ip >> 16) & 0xFF) + "." +
                    (ip >> 24 & 0xFF);
        }
    }
    

    用法

    创建一个服务端

    mSocket server = new mSocket(8848,10);
    

    传入“端口号”+“backlog”参数创建服务器实例,并自动开始监听客户端连入参数。
    注:必须在子线程中启用。

    创建一个客户端

    mSocket client = new mSocket("ip",8848);
    
    

    传入“ip”+”端口号“参数创建客户端实例。

    client.buildConnection();
    

    创建连接的方法,返回true时连接成功,返回false连接失败。
    注:必须在子线程中启用

    获取信息流

    String smessage = client.getMessage();
    

    注:必须在子线程中启用

    发送数据流

    client.sendMessage("message");
    

    可发送对象类,无需在子线程中使用。

    获取本机IP

     String ip = new mSocket().getIPAddress(context);
    

    注:需要添加以下权限

     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     <uses-permission android:name="android.permission.INTERNET"/>
    
  • 相关阅读:
    LNMP
    Unable to guess the mime type as no guessers are available 2 9
    django--模型字段引用
    no python application found, check your startup logs for errors
    uWSGI+django+nginx的工作原理流程与部署历程
    进程管理supervisor的简单说明
    Django 部署(Nginx)
    MyBatis学习教程
    Spring教程
    互联网的寒冬该如何度过
  • 原文地址:https://www.cnblogs.com/Mr-quin/p/9636635.html
Copyright © 2020-2023  润新知