【问题标题】:How to establish a WebSocket connection in android service?如何在android服务中建立WebSocket连接?
【发布时间】:2015-07-17 12:55:04
【问题描述】:

我一直在尝试创建一个 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。我想知道可能是什么原因?

【问题讨论】:

  • 我想你有互联网连接,所以 webSocket 客户端没有正确响应 Android 有很多 websocket 客户端,你使用哪一个?
  • 没有,我的互联网连接正常。我在我的项目中使用了 Java-Websocket-1.3.jar 文件。这是错的吗?我是在 android 中使用 websockets 的新手。
  • 您应该检查您的服务器实现,因为套接字高度依赖于底层协议,如果不同导致连接超时,请在经过测试的客户端下方查看我的答案,他们有代码示例,只需添加它就可以了跨度>
  • 你能解决这个问题吗?

标签: java android websocket


【解决方案1】:

你使用的 websocket 客户端不是那么健壮尝试使用我用于我的项目的引擎 IO 客户端,性能很好 https://github.com/nkzawa/engine.io-client.java 并非所有客户端都与您的服务器兼容检查服务器上正在使用的内容,并且应该使用服务器上的不同库复制连接,客户端会导致连接中断

【讨论】:

  • 感谢您的帮助。我现在就试试。
猜你喜欢
  • 2015-05-19
  • 2012-10-17
  • 2017-04-13
  • 2015-05-19
  • 2021-01-02
  • 1970-01-01
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
相关资源
最近更新 更多