如何从套接字方法获取数据?

时间:2017-10-28 09:46:32

标签: java android sockets

我已使用webSocket库连接到一个套接字。 https://www.varvet.com/blog/using-websockets-in-native-ios-and-android-apps/

编译“org.java-websocket:Java-WebSocket:1.3.0”

现在我想从socket获取数据。

在javascript中代码如下:

socket : io.connect('52.11.67.123:6060', { query: {user:JSON.stringify({user:usercus}) ,login:JSON.stringify({username:'escr',password:'escrowandt'})}}),
thats for connection
MY_Socket.socket.emit('getBids');
      MY_Socket.socket.emit('getHistory');

如何在android中调用此getBid和getHistory?

我的连接套接字代码:

  private void connectWebSocket() {
       URI uri;
       try {
           JSONObject authenticate = new JSONObject();
           authenticate.put("username", "escr");
           authenticate.put("password", "escrowandt");

         Uri.Builder builder = new Uri.Builder();
           builder.scheme("ws")
                   .encodedAuthority("52.11.67.123:6060")
                   .appendEncodedPath("socket.io/")
                   .appendQueryParameter("user", sessionData.getString("customer_id", ""))
                   .appendQueryParameter("login", String.valueOf(authenticate));

           String myUrl = builder.build().toString()+"&EIO=3&transport=websocket";

           Log.e("socket:", myUrl);
           uri = new URI(myUrl);
           Log.e("socket1:", uri.toString());

           mWebSocketClient = new WebSocketClient(uri) {
               @Override
               public void onOpen(ServerHandshake serverHandshake) {
                   Log.i("Websocket", "Opened");
                   mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
                   mWebSocketClient.send("getHistory");
                   mWebSocketClient.send("getBids");
               }



               @Override
               public void onMessage(String s) {
                   final String message = s;
                   runOnUiThread(new Runnable() {
                       @Override
                       public void run() {

                           Log.i("responseFromWebSocket",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();

       }
            catch (JSONException e) {
           }catch (URISyntaxException e) {
               e.printStackTrace();
               return;
           }
   }

请帮忙。谢谢。

0 个答案:

没有答案