的InputStream不读什么 [英] InputStream not reading anything

查看:142
本文介绍了的InputStream不读什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的客户端code.Client发送手机号码。给Servlet。然后servlet将字符串发送给客户端是由Client.Servlet采用base64 EN codeD,然后从Inputstream.But读取从InputStream没有读取该连接codeD字符串。

 私有类SendIP扩展的AsyncTask<太虚,太虚,字符串>
{
    的EditText等;
    整数值;
    保护字符串doInBackground(无效... PARAMS)
    {        尝试
        {               网址URL =新的URL(http://10.0.2.2:8080/New/MyServlet);
               URLConnection的连接= url.openConnection();
               connection.setDoOutput(真);               等=(EditText上)findViewById(R.id.editText1);
               。数= et.getText()的toString();
               OutputStreamWriter出=新OutputStreamWriter(connection.getOutputStream());               out.write(数字+\\ n); //发送手机号码。服务器
               了out.flush();
               out.close();               在的BufferedReader =新的BufferedReader(新的InputStreamReader(connection.getInputStream()));
               消息= in.readLine();
               海峡= in.readLine(); //读取由服务器发送的串               附寄();
               字节[]数据= str.getBytes(UTF-8);
               的base64 = Base64.en codeToString(数据,Base64.DEFAULT); //编码串入的base64
               OutputStreamWriter OUT1 =新OutputStreamWriter(connection.getOutputStream());
               out1.write的(Base64 +\\ n);
               out1.flush(); //发送连接codeD字符串服务器
               out1.close();
               //out.close();
        }
        赶上(例外五)
        {
            e.printStackTrace();
        }
        / *赶上(IOException异常E)
        {
            e.printStackTrace();
        }
        * /

这是我的服务器端code。

 保护无效的doPost(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{
    // TODO自动生成方法存根
    //为PrintWriter了= response.getWriter();    尝试
    {
    中byte buf [] =新的字节[40];
    BYTE B [] =新的字节[40];    ServletInputStream罪= request.getInputStream();    NUM = sin.readLine(BUF,0,buf.length); //读取手机号码。从客户端
    字符串消息=新的String(BUF);
    的System.out.println(消息);    //response.setStatus(HttpServletResponse.SC_OK);    }
        }
          }
      }
OutputStreamWriter作家=新OutputStreamWriter(response.getOutputStream());
    RES =。移动没有获得;
    海峡=你好客户;
    writer.write(RES +\\ n); //发送手机号码到服务器
    writer.write(STR +\\ n); //发送串是EN coded到服务器
    writer.flush();
    NUM1 = sin.readLine(B,0,b.length个); //读取来自客户端的连接codeD字符串
    的base64 =新的String(B);
    的System.out.println(NUM1); //这个版画-1
    sin.close();    response.setStatus(HttpServletResponse.SC_OK);    writer.close();    }
    赶上(IOException异常E)
    {
        。response.getWriter()的println(E);
    }


解决方案

三个问题:


  • 您已设置则将DoOutput 真正,但您没有设置则将DoInput 真正


  • 您服务器端似乎是一个POST请求codeD,但客户端没有设置任何方法类型。 (默认情况下将发送GET请求......)


  • 您没有检查状态的URL连接。如果状态指示错误,那么的getInputStream()会给你一个空流。这可能发生(例如)如果请求永远不会到你的服务器端的doPost 方法...



更新

啊......我看你正在尝试做的。

  OutputStreamWriter OUT1 =
           新OutputStreamWriter(connection.getOutputStream());

我怀疑,将工作。当您关闭了原来的输出流,这应该已经关闭的基本插座输出端。它不能被重新打开。如果它没有关闭插座我期望的getOutputStream()打电话给扔

 的ProtocolException(读取输入后不能写输出。)

基本上, HttpURLConnection类 API并没有设计这样的工作...


您似乎在试图做的是落实喜欢的WebSockets......在客户端和服务器协商的HTTP套接字的HTTP请求后保持打开和回复,然后用于其他的事情的东西。如果你想这样做,你应该看看Java EE的 javax.websocket javax.websocket.server 包;看到这里

有太多的WebSockets的其他实现;谷歌的Java的WebSocket,以及配合客户端和服务器可以在其他非标准的方式做到这一点。但是,这是外面什么HttpURLConnection的API或实施将支持。

This is my Client side code.Client sends mobile no. to the Servlet. Servlet then sends a string to the client which is to be base64 encoded by Client.Servlet then reads this encoded string from Inputstream.But it reads nothing from the Inputstream.

    private class SendIP extends AsyncTask<Void, Void, String>
{
    EditText et; 
    Integer value;
    protected String doInBackground(Void... params) 
    {

        try
        {

               URL url = new URL("http://10.0.2.2:8080/New/MyServlet");
               URLConnection connection = url.openConnection();
               connection.setDoOutput(true);

               et = (EditText) findViewById(R.id.editText1);
               number = et.getText().toString();
               OutputStreamWriter out=new OutputStreamWriter(connection.getOutputStream());

               out.write(number+"\n");//sending mobile no. to server
               out.flush();
               out.close();

               BufferedReader in=new BufferedReader(new InputStreamReader (connection.getInputStream()));
               message=in.readLine();
               str=in.readLine();//reading the string sent by server

               in.close();
               byte[]data=str.getBytes("UTF-8");
               base64=Base64.encodeToString(data, Base64.DEFAULT);//encoding the string into base64
               OutputStreamWriter out1=new OutputStreamWriter(connection.getOutputStream());
               out1.write(base64+"\n");
               out1.flush();//sending the encoded string to server
               out1.close();
               //out.close();






        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        /*catch(IOException e)
        {
            e.printStackTrace();
        }
        */

This is my Server side code.

       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws       ServletException, IOException {
    // TODO Auto-generated method stub
    //PrintWriter out=response.getWriter();

    try
    {
    byte buf[]=new byte[40];
    byte b[]=new byte[40];

    ServletInputStream sin=request.getInputStream();

    num=sin.readLine(buf, 0, buf.length);//reading mobile no. from client
    String message=new String(buf);
    System.out.println(message);

    //response.setStatus(HttpServletResponse.SC_OK);

    }
        }
          }
      }
OutputStreamWriter writer=new  OutputStreamWriter(response.getOutputStream());
    res="mobile no. received";
    str="hello client";
    writer.write(res+"\n");//sending mobile number to server
    writer.write(str+"\n");//sending string to be encoded to server
    writer.flush();
    num1=sin.readLine(b,0,b.length);//reading the encoded string from client
    base64=new String(b);
    System.out.println(num1);//this prints -1
    sin.close();

    response.setStatus(HttpServletResponse.SC_OK);

    writer.close();

    }
    catch(IOException e)
    {
        response.getWriter().println(e);
    }

解决方案

Three problems:

  • You have set doOutput to true, but you haven't set doInput to true.

  • Your server side seems to be coded for a POST request, but the client side is not setting any method type. (It will send a GET request by default ...)

  • You are not checking the status for the URL connection. If the status indicates an error, then getInputStream() will give you an empty stream. That might happen (for example) if the request never gets to your server-side doPost method ...


UPDATE

Ah ... I see what you are trying to do.

    OutputStreamWriter out1 = 
           new OutputStreamWriter(connection.getOutputStream());

I doubt that that will work. When you closed the original output stream, that should have closed the output side of the underlying Socket. It can't be reopened. And if it didn't close the Socket I would expect the getOutputStream() call to throw

    ProtocolException("Cannot write output after reading input.")

Basically, the HttpURLConnection API is not designed to work like this ...


What you appear to be trying to do is to implement something like "websockets" ... where the client and the server negotiate that the HTTP socket is kept open after the HTTP request and reply and is then used for "other things". If you want to do that, you should look at the Java EE javax.websocket and javax.websocket.server packages; see here.

There are other implementations of websockets too; Google for "java websocket", and a cooperating client and server could do this in other non-standard ways. But this is outside what the HttpURLConnection API or implementation will support.

这篇关于的InputStream不读什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆