简体   繁体   English

为什么这个Android Socket程序不起作用?

[英]Why this Android Socket program don't work?

I have connected my Android device to the wifi shared by my laptop. 我已将Android设备连接到笔记本电脑共享的wifi。 After I input the IP address and click "OK" in the Android app, I can not find any packets to/from the address in Wireshark (packet sniffer) 输入IP地址并在Android应用中单击“确定”后,我在Wireshark(数据包嗅探器)中找不到与该地址之间的任何数据包。

I have added this to the manifest of the Android Project: 我已将此添加到Android项目的清单中:

<uses-permission android:name="android.permission.INTERNET"/>

Android Code: Android代码:

    private boolean attemptOpenDoor(){

    // Store values at the time of the login attempt.
    String studentId = mStudentIdView.getText().toString();
    String password = mPasswordView.getText().toString();

    final EditText et = new EditText(this);
    new AlertDialog.Builder(this).setTitle("please input IP address")
            .setIcon(android.R.drawable.ic_dialog_info).setView(et)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    IPAddr =  et.getText().toString();
                }
            }).setNegativeButton("cancel", null).show();

    try {
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(IPAddr, 8866), 5000);
        OutputStream ou = socket.getOutputStream();
        ou.write((studentId+password).getBytes("UTF-8"));
        ou.close();
        socket.close();
    }catch (SocketTimeoutException aa) {
        //连接超时 在UI界面显示消息
        AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
        alertDialog.setMessage("服务器连接失败!请检查网络是否打开");
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        alertDialog.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}

You should move your connect codes after "onClick". 您应该在“ onClick”之后移动连接代码。

new AlertDialog.Builder(this).setTitle("please input IP address")
        .setIcon(android.R.drawable.ic_dialog_info).setView(et)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                IPAddr =  et.getText().toString();
                 try {
    Socket socket = new Socket();
    socket.connect(new InetSocketAddress(IPAddr, 8866), 5000);
    OutputStream ou = socket.getOutputStream();
    ou.write((studentId+password).getBytes("UTF-8"));
    ou.close();
    socket.close();
}catch (SocketTimeoutException aa) {
    //连接超时 在UI界面显示消息
    AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
    alertDialog.setMessage("服务器连接失败!请检查网络是否打开");
    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    alertDialog.show();
} catch (Exception e) {
    e.printStackTrace();
}
            }
        }).setNegativeButton("cancel", null).show();

The program doesn't work because at the time that you're trying to open the socket using: 该程序无法正常工作,因为在您尝试使用以下方法打开套接字时:

socket.connect(new InetSocketAddress(IPAddr, 8866), 5000);

the dialog is still up and value of IPAddr has not yet been set. 对话框仍然打开,并且尚未设置IPAddr值。 Make sure that you only start connecting once the user has entered a valid input in the field. 确保仅在用户在字段中输入有效输入后才开始连接。

Also, beware that the method above will block whichever thread it's running on until a connection is established or 5 seconds go by, meaning that it'd be unwise to call it directly inside of the OnClickListener . 另外,请注意,上述方法将阻塞正在运行的任何线程,直到建立连接或经过5秒钟为止,这意味着在OnClickListener内部直接调用它是不明智的。 You should probably use an AsyncTask or similar to avoid blocking the UI thread while the connection is taking place. 您可能应该使用AsyncTask或类似的方法,以避免在建立连接时阻塞UI线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM