PHP Socket with android

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


If you want to skip what I’ve written, here’s a download to a fully working PHP socket server and Android socket client (with all the source code): http://www.developersfound.com/PHP_SocketServer_Android_SocketClient.zip

Or for information that you may find useful read on ....

An important rule of thumb here is to understand the differences between the ‘HTTP request/response model’ and the TCP model. The advantage of TCP over HTTP is that you can queue messages and take advantage of full duplex (two way simultaneous communication), also open TCP connections are a bit more responsive. Unless your solution absolutely needs queuing and or benefits from full duplex you should actually be using RPC over HTTP or REST. HTTP is much easier to implement and more reliable on mobile devices. Moving long distances on mobile devices, tends to break TCP connections and when the connection is broken you lose any queuing and have to reconnect. Reconnecting also takes up a lot more battery power and can hang the client system. Another disadvantage is that a live system can end up with a lot of live connections and slow your servers quite significantly; more so than a busy HTTP server.

However if your solution needs, or benefits from the advantages of TCP, read on ....

This code base (in the link above) has a fully functional (self contained) PHP server and a fully functional Android socket client. This code base should provide a strong reference for implementing client sockets in Android. This code base is implemented in accordance with Android best practices as well as serving as a strong reference for implementing long running process for stability.

It is noteworthy to understand that the Android docs recommend using Services to implement sockets because sockets cannot be parsed. For this reason a singleton type model is necessary. You will notice that this codebase uses AIDL to communicate with the service and broadcasts to update the UI. This is best practice as sockets must be protected from garbage collection and activity recreation, which would normally break the socket connections. Services bound through the AIDL and Thread Executors are all associated with best practices for the stability of long running processes.

Hope this helps.