java服务器无法向android客户端发送消息

时间:2014-06-12 10:05:01

标签: java android

这是我的客户端代码,它将在Android模拟器上运行。

它首先向服务器发送一个号码和消息,然后服务器将回复

     protected String doInBackground(Void... params) {
        try {

            client = new Socket("10.210.8.168", 4444);
            LocalIP=client.getLocalAddress();
            message=LocalIP.toString();//message stores the IP Address of the client
             et=(EditText)findViewById(R.id.editText1);
            String number=et.getText().toString();//number is to be entered by the user
            pw1 = new PrintWriter(client.getOutputStream(),true);
            pw1.write(number);
            pw1.write(message);
            pw1.flush();
            pw1.close();
            is=new InputStreamReader(client.getInputStream());
            in=new BufferedReader(is);
            text=in.readLine();

            is.close();
            client.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text;

    }
    protected void onPostExecute(String result)
    {
        Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
                et=(EditText)findViewById(R.id.editText1);
         et.setText("");


     }

这是我的java服务器。 它会向Android客户端发送消息 //服务器首先读取客户端发送的消息和号码。然后发送消息" mobile no.received"到客户

while(true)
    {

        try
        {


            //System.out.println("hello");
            //serversocket.setSoTimeout(1000);
            //System.out.println("please");
            client=serversocket.accept();
            is1=new InputStreamReader(client.getInputStream());
            br1=new BufferedReader(is1);
             message=br1.readLine();
            System.out.println(message);
              /*pw=new PrintWriter(client.getOutputStream(),true);
            pw.write("mobile number received\n");
            pw.flush();
            pw.close();
            */
            OutputStream os=client.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(os);
            BufferedWriter bw=new BufferedWriter(osw);
            bw.write("mobile number received\n");
            bw.flush();


            client.close();
             //is1.close();


                    /*add=serversocket.getInetAddress();
                    remoteIP=add.getHostAddress();
                    System.out.println(remoteIP);*/

            //System.out.println("this is working");

           //client.close();

        }
        catch(IOException e)
        {
            System.out.println("cannot read message"+e);
        }
 }

0 个答案:

没有答案