如何绑定android socket.io连接和断开按钮?

时间:2015-08-19 01:23:01

标签: java android button socket.io

所以基本上它的作用是有一个显示器,其中包含一个带有用户ID的editText,两个按钮:连接和断开连接,以及反映该状态的文本视图。目前发生的事情是用户可以输入他们的ID并连接并从他们连接的服务器接收消息,但随后连接就会丢失。

  

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.MalformedURLException;
import java.net.URL;

import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String SERVER_ADDRESS = "";
    TextView textView_state;
    EditText editText_ID;
    Button button_connect;
    Button button_disconnect;
    SocketIO socket;

    public String getUserID() {
        String string = editText_ID.getText().toString();
        if (string.length() > 0) {
            return string;
        }
        else {
            return null;
        }
    }

    public JSONObject packageClient (String s) throws JSONException {
        if (s != null) {
            JSONObject obj = new JSONObject();
            obj.put("client",s);
            return obj;
        }
        else {
            return null;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText_ID = (EditText) findViewById(R.id.editText_ID);
        textView_state = (TextView) findViewById(R.id.textView_state);
        button_connect = (Button) findViewById(R.id.button_connect);
        button_disconnect = (Button) findViewById(R.id.button_disconnect);

        button_connect.setOnClickListener(this);
        button_disconnect.setOnClickListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        final String client = getUserID();
        if (client != null) {
            switch (v.getId()) {
                case R.id.button_connect:
                    try {
                        socket = new SocketIO(new URL(SERVER_ADDRESS));
                        socket.connect(new IOCallback() {
                            @Override
                            public void onDisconnect() {
                                System.out.println("Connection terminated, from connect button.");

                            }

                            @Override
                            public void onConnect() {
                                System.out.println("Connection established");
                                try {
                                    JSONObject data = packageClient(client);
                                    socket.emit("create_user_room", data);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onMessage(String s, IOAcknowledge ioAcknowledge) {

                            }

                            @Override
                            public void onMessage(JSONObject jsonObject, IOAcknowledge ioAcknowledge) {

                            }

                            @Override
                            public void on(String s, IOAcknowledge ioAcknowledge, Object... objects) {
                                if ("client_connected".equals(s)) {
                                    textView_state.setText("Connected");
                                }
                                if ("client_disconnected".equals(s)) {
                                    textView_state.setText("Disconnected");
                                }
                            }

                            @Override
                            public void onError(SocketIOException e) {

                            }
                        });
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.button_disconnect:
                    try {
                        JSONObject data = packageClient(client);
                        socket.emit("request_disconnect", data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }
}

在我的android sdk上我得到了这个输出:

08-18 17:37:49.400  22449-22518/I/io.socket﹕ < 1::
08-18 17:37:49.402  22449-22518/I/io.socket﹕ > 1::/lobby:
08-18 17:37:49.414  22449-22518/I/io.socket﹕ < 1::/lobby
08-18 17:37:49.415  22449-22518/I/System.out﹕ Connection established
08-18 17:37:49.415  22449-22518/I/io.socket﹕ > 5::/lobby:{"name":"create_user_room","args":[{"client":"121"}]}
08-18 17:37:49.431  22449-22518/I/io.socket﹕ < 5::/lobby:{"args": [], "name": "client_connected"}
08-18 17:37:49.434  22449-22518/I/io.socket﹕ Cleanup

在我的服务器上,我得到了这个输出:

2015-08-18 17:38:05,281 - INFO | Client connected
2015-08-18 17:38:05,297 - INFO | Creating room for 121
2015-08-18 17:38:05,298 - INFO | Room 121 created for 121
2015-08-18 17:38:30,222 - INFO | Client disconnected

[两个不同的物理机器之间可能会有轻微的时间断开连接]

我认为它正在围绕着#34; Cleanup&#34;命令,我认为它可能与通过按钮调用连接的方式有关。当我将 case R.id.button_connect:下的所有内容移动到 protected void onCreate(Bundle savedInstanceState)时,一切仍然有效,并且连接停留并按下断开连接按钮会断开用户连接:

08-18 18:08:07.816    2011-2011/I/io.socket﹕ > 5::/lobby:{"name":"request_disconnect","args":[{"client":"121"}]}
08-18 18:08:07.827    2011-2043/I/io.socket﹕ < 5::/lobby:{"args": [], "name": "client_disconnected"}
08-18 18:08:07.828    2011-2043/I/io.socket﹕ Cleanup
08-18 18:08:07.829    2011-2043/I/io.socket﹕ < 0::/lobby
08-18 18:08:07.829    2011-2043/I/io.socket﹕ Cleanup

它说了两次,不知道为什么。有谁知道我如何正确设置并调用这段代码,以便它可以解决我的连接按钮?

0 个答案:

没有答案