如何在android服务中建立WebSocket连接?

时间:2015-07-17 12:55:05

标签: java android websocket

我一直在尝试创建一个Android服务,这将允许我维护websocket连接并及时发送一些数据。我在服务中创建一个处理程序来连接WebSocketClient。但它没有连接。网址正在运行,我也测试了它。如果有人能提供帮助,我深表感谢。

主要Activity.java

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BroadcastReceiver receiver=new BroadcastReceiver() {

    @Override
        public void onReceive(Context context, Intent intent) {
            TextView text=(TextView) findViewById(R.id.textView);
            text.setText(intent.getStringExtra("msg"));

        }
    };

    registerReceiver(receiver, new IntentFilter(SocketService.BROADCAST_ACTION));

    }


    // Method to start the service
    public void startService(View view) {
        startService(new Intent(getBaseContext(), SocketService.class));
    }

    // Method to stop the service
    public void stopService(View view) {
        stopService(new Intent(getBaseContext(), SocketService.class));
    }



}

服务实施

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

import java.util.logging.LogRecord;

public class SocketService extends Service {

    boolean status=false;
    public static final String BROADCAST_ACTION = "com.supun.broadcasttest";
    BroadcastReceiver broadcaster;
    BroadcastReceiver broadreciever;
    Intent intent;
    Handler handler;
    WebSocketClient client;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        intent=new Intent(BROADCAST_ACTION);
        handler=new Handler();

    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
         Toast.makeText(this, "Service Started",Toast.LENGTH_LONG).show();// Let it continue running until it is stopped.
         ////////////////////////////////////////////////////////////////////////////////


        try {
            client = new WebSocketClient(new URI(
                    "ws://xxxxxxx-xxxx.rhcloud.com:8000/browser")) {

                @Override
                 public void onOpen(ServerHandshake handshakedata) {
                    Log.d("1", "open");
                    status = true;

                }

                @Override
                public void onMessage(String message) {


                    Log.d("reply", message);
                    intent.putExtra("msg", message);
                    sendBroadcast(intent);

                }

                @Override
                public void onError(Exception ex) {
                     // TODO Auto-generated method stub

                }

                @Override
                public void onClose(int code, String reason, boolean remote{
                    status = false;

                }
            };




        }catch(Exception e){


        }
            ///////////////////////////////////////////////////////////////////////////////

//
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, 1000);
        return START_STICKY;
    }




    private Runnable runnable=new Runnable() {
        @Override
        public void run() {
            client.connect();

            for(int i=0; i<5;i++){
                if(status){
                    intent.putExtra("msg","open");
                    sendBroadcast(intent);
                    break;
                }else{
                    try {
                        intent.putExtra("msg",client.getReadyState().toString());
                        sendBroadcast(intent);
                        Thread.sleep(1000);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            if (!status) {
                intent.putExtra("msg","Time Out");
                sendBroadcast(intent);

            }



        }
    };





    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

我正在通过按钮单击事件调用Main Activity中的启动服务方法。输出总是快速转到Closing,最后显示为Timed out。我想知道可能是什么原因?

1 个答案:

答案 0 :(得分:0)

使用的websocket客户端不是那种使用我用于项目的Engine IO客户端的强大尝试,性能卓越 https://github.com/nkzawa/engine.io-client.java 并非所有客户端都与您的服务器兼容,检查服务器上正在使用的内容,并且应该使用服务器上的不同库来复制该连接,并且客户端会导致连接断开