3

我正在研究高速公路网络套接字通信。我的应用程序中有一个轮播视图,有四个图像。当用户单击图像时,然后使用 websocket 连接到服务器并发送消息。但问题是,当我选择图像时,它会正确连接到服务器,但客户端(android 设备)每次发送消息时都会连接到 websocket。这是我的代码..

if (pos == 0) {
    product_photo.setImageResource(R.drawable.myoffers_0);
    product_photo.setOnClickListener(new ImageButton.OnClickListener(){
        public void onClick(View v){
            String id = "Product0";
            Log.d(TAG, "Current product is : " + id);
            A.sendMessage(id);  
        }
    });
}

Websocket.class

public class WebSocket_Connector extends Activity{

    private static final String TAG = "ECHOCLIENT";
    private static final String TAG1 = "My app";
    public final WebSocketConnection mConnection = new WebSocketConnection();
    private String tmpString = "";

    public void connect(final String wsuri) {

          Log.d(TAG, "Connecting to: " + wsuri); 

          try {
             mConnection.connect(wsuri, new WebSocketHandler() {

                @Override
                public void onOpen() {
                   Log.d(TAG, "Status: Connected to " + wsuri ); 
                   Log.d(TAG, "Connection successful!\n");
                   mConnection.sendTextMessage(tmpString); 
                   tmpString = "";
                }

                @Override
                public void onTextMessage(String payload) {
                   Log.d(TAG, "Got echo: " + payload);
                }

                @Override
                public void onClose(int code, String reason) {
                   Log.d(TAG, "Connection closed.");
                }
             });
          } catch (WebSocketException e) {

             Log.d(TAG, e.toString());
          }
       }

    public void sendMessage(String message) {
        if (mConnection.isConnected()) {
            Log.d(TAG1, "Messeage is sent : " + message);
            mConnection.sendTextMessage(message); 

        }
        else {
            tmpString = message;
            connect("ws://xxx.xxx.x.xxx:xxxx");
        }
    }   
}

它不会去'if(mConnection.isConnected())'这里..总是去其他地方。

4

0 回答 0