2017-01-16 6 views
2

現在、ネットワークコールにはokhttpを使用しています。また、私はこのようにそれを作ったので、WebSocketのものが必要ですokhttp3 websocketでSTOMPを使用することはできますか?


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); 
     } 
    } 
} 
} 

しかし、私がする必要があることは例/ライブラリにhttps://github.com/NaikSoftware/StompProtocolAndroid

のようなウェブソケットにSTOMPを使用できるようにすることです

スタンプと一緒にokhttpを使用する方法や例がある場合は、あなたが言及した場合は助けになります。 また、上記のライブラリを使用して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を使用したスト​​ンプ例を挙げることができる場合にも役立つだろう。

答えて

関連する問題