zoukankan      html  css  js  c++  java
  • 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"/>
    
  • 相关阅读:
    在Centos7下源代码安装配置Nginx
    mysql5.7.21源码安装
    数据库设计三大范式
    电商项目中使用Redis实现秒杀功能
    PHP和Redis实现在高并发下的抢购及秒杀功能示例详解
    PHP面向对象(抽象类与抽象方法、接口的实现)
    php面向对象 封装继承多态 接口、重载、抽象类、最终类总结
    利用VHD虚拟文件加密自己的个人信息
    Chrome常用快捷键
    stl本子
  • 原文地址:https://www.cnblogs.com/Mr-quin/p/9636635.html
Copyright © 2011-2022 走看看