Herramienta de comunicación de socket para el servidor de simulación de Android para enviar mensajes

Herramienta de comunicación de socket para el servidor de simulación de Android para enviar mensajes

1. Antecedentes

Introducción previa:
algunos escenarios deben depender del servidor para enviar mensajes al cliente, como PowerMsg, el servidor envía el tipo de mensaje y el cliente analiza el tipo para realizar las acciones correspondientes. Por ejemplo, las preguntas de respuesta en vivo deben depender del servidor para enviar mensajes, y el cliente recibe los mensajes para mostrar las preguntas de acuerdo con las reglas, etc.

2. Explicación de los puntos débiles

Confiando en el envío de mensajes desde el servidor, el cliente es muy pasivo y no puede construir activamente los mensajes correspondientes. Por lo tanto, existe una necesidad urgente de una herramienta que pueda simular la entrega de mensajes del lado del servidor, y la herramienta de socket proviene de esto.

3. Principio de la herramienta

La computadora simula el servidor de Socket, la aplicación de Android simula el cliente de Socket y envía mensajes al cliente a través de la herramienta de socket.

4. Código de cliente de socket

if (ConfigHelper.getInstance().getAppConfig().isDebug()
            && PreferenceCommon.getInstance().getBoolean("is_xx_socket_enable", false)) {
    
    
            Socket2PowerMsgTool.getInstance().setLiveMessageParserCallBack(this)
            Socket2PowerMsgTool.getInstance().startSocket()
        }

Socket2PowerMsgTool.java

public class Socket2PowerMsgTool {
    
    

    private static final String SocketIP = "30.5.195.154";
    private static final int SocketPort = 7654;

    Socket socket = null;
    private String recv_buff = null;

    private static Socket2PowerMsgTool instance = new Socket2PowerMsgTool();

    private Socket2PowerMsgTool(){
    
    
    }

    public static Socket2PowerMsgTool getInstance(){
    
    
        return instance;
    }

    private ILiveMessageParserCallBack mLiveMessageParserCallBack;

    public void setLiveMessageParserCallBack(ILiveMessageParserCallBack mLiveMessageParserCallBack) {
    
    
        this.mLiveMessageParserCallBack = mLiveMessageParserCallBack;
    }

    public void startSocket() {
    
    
        String ip = PreferenceCommon.getInstance().getString("live_mock_socket_ip", "");
        String portString = PreferenceCommon.getInstance().getString("live_mock_socket_port", "");
        if (TextUtils.isEmpty(ip) || TextUtils.isEmpty(portString)) {
    
    
            return;
        }
        int port = Integer.parseInt(portString);

        new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                try {
    
    
                    //连接到指定的IP和端口号,并指定10s的超时时间
                    socket = new Socket();
                    socket.connect(new InetSocketAddress(ip, port), 10000);
                    if (socket != null && socket.isConnected()) {
    
    
                        while(true) {
    
    
                            recv();
                        }
                    }
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void recv() {
    
    
        InputStream inputStream = null;
        try {
    
    
            inputStream = socket.getInputStream();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        if (inputStream != null){
    
    
            try {
    
    
                byte[] buffer = new byte[1024];
                int count = inputStream.read(buffer);//count是传输的字节数
                recv_buff = new String(buffer);//socket通信传输的是byte类型,需要转为String类型
                recv_buff = recv_buff.substring(0, count);
                String regex="^[A-Fa-f0-9]+$";
                if (recv_buff.matches(regex)) {
    
    
                    recv_buff = hexStringToString(recv_buff);
                }
                Log.i("ruihan-test", recv_buff);
                if (!TextUtils.isEmpty(recv_buff) && isJSONString(recv_buff)) {
    
    
                    MockPowerMsgEntity mockPowerMsgEntity = FastJsonUtil.json2pojo(recv_buff, MockPowerMsgEntity.class);
                    if(mockPowerMsgEntity != null) {
    
    
                        if (mockPowerMsgEntity.type == 1) {
    
    
                            if (mLiveMessageParserCallBack != null) {
    
    
                                mLiveMessageParserCallBack
                                        .msgLiveOriginalJsonPaserCallBack(FastJsonUtil.pojo2json(mockPowerMsgEntity.data));
                            }
                        } else if (mockPowerMsgEntity.type == 2) {
    
    
                            if (mLiveMessageParserCallBack != null) {
    
    
                                mLiveMessageParserCallBack
                                        .msgLikeParserCallback(JSONObject.toJavaObject(mockPowerMsgEntity.data, MsgLike.class));
                            }
                        } else if (mockPowerMsgEntity.type == 3) {
    
    
                            if (mLiveMessageParserCallBack != null) {
    
    
                                mLiveMessageParserCallBack
                                        .msgLiveStatusParserCallback(FastJsonUtil.pojo2json(mockPowerMsgEntity.data),
                                                JSONObject.toJavaObject(mockPowerMsgEntity.data, MsgLiveStatus.class));
                            }
                        }
                    }
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    private String hexStringToString(String s) {
    
    
        if (s == null || s.equals("")) {
    
    
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
    
    
            try {
    
    
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
    
    
                e.printStackTrace();
            }
        }
        try {
    
    
            s = new String(baKeyword, "UTF-8");
            new String();
        } catch (Exception e1) {
    
    
            e1.printStackTrace();
        }
        return s;
    }

    public boolean isJSONString(String str) {
    
    
        boolean result = false;
        try {
    
    
            Object obj = JSONObject.parse(str);
            result = true;
        } catch (Exception e) {
    
    
            result = false;
        }
        return result;
    }

    public void closeSocket() {
    
    
        try {
    
    
            if (socket!= null) {
    
    
                socket.close();
                socket = null;
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

Implementación de devolución de llamada de interfaz:

override fun msgLiveOriginalJsonPaserCallBack(jsonString: String?) {
    
    
        val isBenefitType = LiveRoomUtils.isBenefitCoupon(jsonString)
        if (isBenefitType) {
    
    
            // TODO
            return
        }
        val isOldHighLightType = LiveRoomUtils.isOldHighLightType(jsonString)
        if (isOldHighLightType) {
    
    
            return
        }
        val isNativeHighLight = LiveRoomUtils.isNativeHighLight(jsonString, mLiveId)
        if (isNativeHighLight) {
    
    
            // TODO
        }
        val isAnswerType = LiveRoomUtils.isAnswerType(jsonString)
        if (isAnswerType) {
    
    
            // TODO
        }
        eventBusFire(WeexEventConstants.WEEX_EVENT_BIND_POWER_MESSAGE_CALLBACK,
                JSONObject.parse(jsonString))
    }

MockPowerMsgEntity.java

public class MockPowerMsgEntity implements Serializable {
    
    

    /**
     *  type 1 2 3 分别对应下列3个回调
     *  fun msgLiveOriginalJsonPaserCallBack(jsonString: String?)
     *  fun msgLikeParserCallback(msgLike: MsgLike)
     *  fun msgLiveStatusParserCallback(jsonString: String?, msgLiveStatus: MsgLiveStatus?)
     *
     */
    public int type;  // 对应 PowerMsg 三种回调类型
    public JSONObject data; // 数据类型

}

5. Herramientas de servidor de socket

1. Instale el programa

Instalar software: SSokit
Dirección SSokit

2. Referencia de paso

1. Abra el software, identifique automáticamente la dirección actual de la computadora, ingrese manualmente el número de puerto, como: 7653
2. Agite el teléfono, ingrese la IP, el número de puerto, haga clic en el botón para configurar el PowerMsg simulado, encienda el interruptor.
3. Pantalla conectada
4. Enviar texto en el cuadro de entrada a la derecha, referencia de formato:

{
    
    
    "type": 1,
    "data": {
    
    
	    "uniqueKey":"1629428186122:-875441502",
	    "type":1304,
	    "body":{
    
    
	        "questionId":12312312312312
	    }
    }

Referencia de configuración de terminal móvil:Referencia de configuración de terminal móvil

3. Envía un mensaje:

inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/adayabetter/article/details/120862700
Recomendado
Clasificación