Eumenides-Z 2018-07-14 14:45 采纳率: 100%
浏览 4008
已结题

Android作为Socket通信客户端的代码分析

基于Android Studio编写Socket的客户端,与基于Python的Socket服务器进行通信。
这是MainActivity相关代码:

    import android.annotation.SuppressLint;
    import android.os.Handler;
    import android.os.Message;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.view.View.OnClickListener;
    import android.os.Bundle;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import  java.net.Socket;

    public class MainActivity extends AppCompatActivity {
    private TextView result = null;
    private TextView result2 = null;
    private static final String HOST = "192.168.80.100";
    private static final int PORT = 12345;
    private Socket socket = null;
    private BufferedReader bufferedReader = null;
    private PrintWriter printWriter = null;
    private String content = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText eturl= findViewById(R.id.eturl);
        Button btn= findViewById(R.id.btn);
        result = findViewById(R.id.result);
        result2 = findViewById(R.id.result2);

        initSocket();
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg;
                msg = eturl.getText().toString();
                if (socket.isConnected()){
                    if (!socket.isOutputShutdown()){
                        Toast.makeText(MainActivity.this,"正在发送,请稍等……",Toast.LENGTH_LONG).show();
                        sendMsg(msg);
                        result.setText("正在连接" + HOST + "\n" + "发送URL" + "\n" + "等待接收检测结果" + "\n");
                        recv();
                    }
                }
            }
        });
    }

    public void sendMsg(final String msg){
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(socket.isConnected()){
                    if(!socket.isOutputShutdown()){
                        printWriter.println(msg);
                    }
                }
            }
        }).start();
    }

    public void initSocket(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    socket=new Socket(HOST,PORT);
                    bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    printWriter=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void recv(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    while (true){
                        if(socket.isConnected()){
                            if(!socket.isInputShutdown()){
                                if((content = bufferedReader.readLine()) != null){
                                    content += "\n";
                                    mhandler.sendMessage(mhandler.obtainMessage());
                                }else{
                                }
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    public Handler mhandler = new Handler(){
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            result2.setText(content);
        }
    };

    }

目前可以正常发送,但接收时有些问题,收不到,安卓客户端没有任何显示。服务器端用另外基于Python的客户端测试过,没问题,应该就是安卓客户端与接收有关的代码可能有问题。
从上面的代码中能看出有什么不妥吗,急求大神指点!!!

  • 写回答

2条回答 默认 最新

  • devmiao 2018-07-14 14:55
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项