PHP Socket with android

前端 未结 2 646
无人共我
无人共我 2020-12-16 05:35

I would like to ask how to create a PHP socket which able receive request from android phone in real time? For now, i done this part of code and able test it using telnet. H

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 05:49

    Add this library in build.gradle.

       compile "org.java-websocket:Java-WebSocket:1.3.0"
    

    to connect:

     private void connectWebSocket() {
        URI uri;
        try {
            uri = new URI("ws://websockethost:8080");
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return;
        }
    
        mWebSocketClient = new WebSocketClient(uri) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                Log.i("Websocket", "Opened");
                mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
            }
    
            @Override
            public void onMessage(String s) {
                final String message = s;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView textView = (TextView)findViewById(R.id.messages);
                        textView.setText(textView.getText() + "\n" + message);
                    }
                });
            }
    
            @Override
            public void onClose(int i, String s, boolean b) {
                Log.i("Websocket", "Closed " + s);
            }
    
            @Override
            public void onError(Exception e) {
                Log.i("Websocket", "Error " + e.getMessage());
            }
        };
        mWebSocketClient.connect();
    }
    

    to send message:

    public void sendMessage(String message) {
        mWebSocketClient.send(message);
    }
    

    ref:https://github.com/elabs/mobile-websocket-example

提交回复
热议问题