开发者社区> 问答> 正文

android socket client 第二次连接异常? 400 报错

android socket client 第二次连接异常? 400 报错

public class SocketClient extends Application implements Runnable{
 private Socket socket = null;
 private String requestMsg = null;
 
 public void setRequestMsg(String requestMsg) {
  this.requestMsg = requestMsg;
 }

 public Socket getSocket() {
  return socket;
 }

 public boolean isAlive(){
  return this.socket.isConnected();
 }
 
 public void init(String dstName, int dstPort){
  try {
   if(this.socket == null){
    this.socket = new Socket(dstName,dstPort);
    this.socket.setTcpNoDelay(true);
    this.socket.setKeepAlive(true);
    this.socket.setSoTimeout(StrConst.timeOut);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 public String Interaction(String requestStr){
  String res = new String();
  try {
   socket = new Socket("220.250.1.142",9000);
   Log.v("请求串:",requestStr);
   PrintWriter out = new PrintWriter(this.socket.getOutputStream());
   out.write(requestStr);
   out.flush();
   BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
   String str = null;
   while((str = in.readLine()) != null){
    res += str + StrConst.KENTER;
   }
   Log.v("返回串:",res + "===");
  }catch(Exception e) {
   e.printStackTrace();
  }
  return res;
 }

 public void close(){
  try{
   if(isAlive()){
    this.socket.shutdownInput();
    this.socket.shutdownOutput();
    this.socket.close();
   }
  }catch(Exception e) {
   e.printStackTrace();
  }
 }

 public String getData(){
  String res = new String();
  try {
   BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
   String str = new String();
   while((str = in.readLine()) != null){
    res += str + StrConst.KENTER;
   }
   Log.v("线程返回串:",res);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return res;
 }
 @Override
 public void run() {
  
  while (true) {
   try {
    Log.v("线程请求串:",requestMsg);
    PrintWriter out = new PrintWriter(this.socket.getOutputStream());
    out.write(requestMsg);
    out.flush();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
}


这是我的socketclient类

当在loginactivity 调用init(),Interaction时 可以得到正确的返回串 可是当跳转到另外一个activity的时候调用Interaction获取返回串的时候 BufferedReader in 获取到的为null (请求串是正确的)  请问这是为啥? 希望能有大神解答下?  被这个问题困扰好久了...

展开
收起
爱吃鱼的程序员 2020-06-02 17:42:05 727 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    发现是 plainsocketimpl.inputstream 关闭了 为啥会关闭?  难道是不同的activity造成的 还是?

    2020-06-02 17:42:22
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载