是否可以将 STOMP 与 okhttp3 websocket 一起使用?

Is it possible to use STOMP with okhttp3 websocket?

我目前正在使用 okhttp 进行网络调用。我也需要 websocket 所以我这样做了:


public class WebSocketService extends Service implements WebSocketListener {
private static final String TAG = "WebSocketService";
private static final String BASE_URL = "ws://192.168.1.39:8080/websocket";

public static final int MSG_RESPONSE = 1;
public static final int MSG_HELLO = 2;
Messenger msger = new Messenger(new MessageHandler());
private WebSocket webSocket;
private boolean mWebSocketOpened = false;
private Messenger replyToMsngr;

@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "service oncreate");
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .readTimeout(0, TimeUnit.NANOSECONDS)
            .connectTimeout(15000, TimeUnit.MILLISECONDS)
            .retryOnConnectionFailure(true)
            .build();
    Request request = new Request.Builder().url(BASE_URL).build();
    WebSocketCall webSocketCall = WebSocketCall.create(okHttpClient, request);
    webSocketCall.enqueue(this);
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    Log.i(TAG, "onBind");
    return msger.getBinder(); //using Messenger
}

@Override
public boolean onUnbind(Intent intent) {
    Log.i(TAG, "onUnbind");
    stopSelf();
    return super.onUnbind(intent);
}

@Override
public void onOpen(WebSocket webSocket, Response response) {
    Log.i(TAG, "On Open"+response.toString());
    this.webSocket = webSocket;
    mWebSocketOpened = true;
    sendMessage(data);
}

@Override
public void onFailure(IOException e, Response response) {
    Log.i(TAG, "onFailure " + e.getMessage());
    e.printStackTrace();
    mWebSocketOpened = false;
}

@Override
public void onMessage(ResponseBody message) throws IOException {
    byte[] bytes = message.bytes();
    if(message.contentType()==WebSocket.TEXT){
        String newString = new String(bytes);

        Message msg = Message.obtain(null, MSG_RESPONSE, 0,0);
        msg.replyTo = replyToMsngr;
        Bundle bundle = new Bundle();
        bundle.putString("rec", newString);
        msg.setData(bundle);

        try {
            replyToMsngr.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    message.close();
}

@Override
public void onPong(Buffer payload) {
    Log.i(TAG, "onPong");
}

@Override
public void onClose(int code, String reason) {
    mWebSocketOpened = false;
}

public class WebSocketBinder extends Binder{
    public WebSocketService getService() {
        // Return this instance of LocalService so clients can call public methods
        return WebSocketService.this;
    }
}

public void sendMessage(String msg){
    Log.i(TAG, "sendMessage : "+msg);
    if(mWebSocketOpened & webSocket!=null){
        try {
            RequestBody requestBody = RequestBody.create(WebSocket.TEXT, msg);
            webSocket.sendMessage(requestBody);

        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
    }else{
        Log.e(TAG, "socket not connected");
    }
}

//test func
public int getRandomNumber(){
    return new Random().nextInt(100);
}

public class MessageHandler extends android.os.Handler {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_RESPONSE:
                Bundle data = msg.getData();
                replyToMsngr = msg.replyTo;
                WebSocketService.this.sendMessage(data.getString("rec", "No data"));
                break;
            case MSG_HELLO:
                Toast.makeText(getApplicationContext(), "heelo", Toast.LENGTH_SHORT).show();
                break;
            default:
                super.handleMessage(msg);
        }
    }
}
}

但我需要做的是能够像在 example/library https://github.com/NaikSoftware/StompProtocolAndroid

中那样在网络套接字中使用 STOMP

如果有任何方法/示例可以将 okhttp 与 stomp 一起使用,如果您提到它会对我有所帮助。 另外,如果需要使用上述库成功实现 websocket,我就是这样实现的。


public class TestActivity extends AppCompatActivity {

private static final String TAG = "testactivity";
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.ettext)
EditText ettext;
@BindView(R.id.content_test)
RelativeLayout contentTest;
@BindView(R.id.fab)
FloatingActionButton fab;
private StompClient mStompCLient;
private static final String BASE_URL = "ws://192.168.1.39:8080/websocket";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    ButterKnife.bind(this);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mStompCLient = Stomp.over(WebSocket.class, BASE_URL);

    mStompCLient.topic("/topic/greetings").subscribe(topicMessage -> {
        Log.d(TAG, topicMessage.getPayload());
    });

    mStompCLient.send("/app/hello", "{\"userName\":\"abcd\"}").subscribe();

    mStompCLient.lifecycle().subscribe(lifecycleEvent -> {
        switch (lifecycleEvent.getType()) {

            case OPENED:
                Log.d(TAG, "Stomp connection opened");
                break;

            case ERROR:
                Log.e(TAG, "Error", lifecycleEvent.getException());
                break;

            case CLOSED:
                Log.d(TAG, "Stomp connection closed");
                break;
        }
    });

    mStompCLient.connect();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            JSONObject object = new JSONObject();
            try {
                object.put("name", ettext.getText().toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Log.i(TAG, "send data : "+ object.toString());
            mStompCLient.send("/app/hello", object.toString()).subscribe();
        }
    });
}

@Override
protected void onStop() {
    super.onStop();
    disconnectStomp();
}

private void disconnectStomp() {
    mStompCLient.disconnect();
}

}

如果有人可以提及使用 okhttp websocket 的 stomp 示例,这也会有所帮助。

您现在可以拨打 Stomp.over(okhttp3.WebSocket.class)