android成功连接并发送消息后从java服务器接收字符串

时间:2012-02-15 13:48:50

标签: android sockets client-server

(编辑我的问题)我有一个工作的android客户端,每秒都会向java服务器发送数据。简单的java服务器连续接收数据没有问题。我想要的是android客户端从服务器接收回复成功传输(从android到服务器的数据),我希望将该回复放在文本视图中。我尝试插入一些代码,但无法弄清楚我如何接收并在客户端文本视图中显示“确定”。 (顺便说一下,网络部分实现了异步任务)

   public static void connect(String name, int port)
        throws UnknownHostException, IOException
{

    s = new Socket(name, port);
    out = new PrintWriter(s.getOutputStream(), true);
     input = new BufferedReader(new InputStreamReader(s.getInputStream()));
}

/**
 * Sends a string message to the server.
 * 
 * @param msg
 *            The message to be sent.
 * @throws IOException
 */
 public static void send(String msg) throws IOException
{
    if (!s.isClosed() && msg != null)
    {
        out.println(msg);

        out.close();                                
    }


}
 public static String receive() throws IOException
 {
     if (!s.isClosed())
     {
         result1 = input.readLine();

            out.close(); 
            input.close(); 
            s.close();


     }
    return result1;


 }

  //Used for receiving notifications from the LocationManager when the location has changed

private class MyLocationListener implements LocationListener{


    @Override
    public void onLocationChanged(Location loc) {
        String txt = "Latitude:" + loc.getLatitude() + "/nLongitude:" + loc.getLongitude();
        Log.i("GeoLocation", "My current location is:\n " + txt);
        tv.setText("My current location is:\n" + txt);
        String msg=loc.getLongitude() + "\n" + loc.getLatitude() + "\n"
        + loc.getTime();
        tv1 = (TextView) findViewById(R.id.textView2);
        tv2 = (TextView) findViewById(R.id.textView3);  
        tv3 = (TextView) findViewById(R.id.textView4);
        //determines if the location is within a designated area (rectangle)
        double lat0 = 14.609794;
        double long0 = 120.986018;
        double lat1 = 14.608966;
        double long1 = 120.986037;
        double lat2 = 14.609031;
        double long2 = 120.984991;
        double lat3 = 14.609877;
        double long3 = 120.985069;
        double rel1 = (loc.getLongitude()- long0)*(lat1 - lat0)- ((loc.getLatitude()-lat0)*(long1-long0));
        double rel2 = (loc.getLongitude()- long1)*(lat2 - lat1)- ((loc.getLatitude()-lat1)*(long2-long1));
        double rel3 = (loc.getLongitude()- long2)*(lat3 - lat2)- ((loc.getLatitude()-lat2)*(long3-long2));
        double rel4 = (loc.getLongitude()- long3)*(lat0 - lat3)- ((loc.getLatitude()-lat3)*(long0-long3));

        // if yes, it will connect to server and send the location and timestamp

       if (rel1 >= 0 && rel2 >= 0 && rel3 >= 0 && rel4 >= 0 )
        {
           tv1.setText("Location is inside the road network...");
           new connectSend().execute(msg);  



          // new receiveString().execute();
           }


        else
        {
            tv1.setText("Current location is outside the road network");

        }
        }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    public class connectSend extends AsyncTask<String, String, String>{

        @Override
        protected String doInBackground(String... msg) {
            // TODO Auto-generated method stub
            String result;

            try
            {
            connect("192.168.10.191", 7774);
            send(msg[0]);
            result = "Sending is SUCCESSFUL ";
            receive();
            publishProgress(result1);

            }

            catch (UnknownHostException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
                result = "Sending NOT SUCCESSFUL ";
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
                result = "Sending NOT SUCCESSFUL ";
            }

            return result;
        }
        @Override
        protected void onProgressUpdate(String... result1) 
        {
                super.onProgressUpdate(result1);
                tv3.setText(result1[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            tv2.setText(result);

}}    

}

}

如果需要,下面是一个简单的java服务器,它通过套接字接收数据并在接收成功时回复

class ChatServer {
private static int port = 1234; /* port to listen on */

public static void main (String[] args) throws IOException {

    class ClientConn implements Runnable {
        private Socket client;

        ClientConn(Socket client) {
            this.client = client;
        }

        public void run() {
            BufferedReader in = null;
            PrintWriter out = null;
            try {
                /* obtain an input stream to this client ... */
                in = new BufferedReader(new InputStreamReader(
                            client.getInputStream()));
                /* ... and an output stream to the same client */
                out = new PrintWriter(client.getOutputStream(), true);
            } catch (IOException e) {
                System.err.println(e);
                return;
            }

            String msg;
            try {
                /* loop reading messages from the client, 
                 * output to stdin and send back an "OK" back */
                while ((msg = in.readLine()) != null) {
                    System.out.println("Client says: " + msg);
                    out.println("OK");
                }
            } catch (IOException e) {
                System.err.println(e);
            }
        }
    }

    ServerSocket server = null;
    try {
        server = new ServerSocket(port); /* start listening on the port */
    } catch (IOException e) {
        System.err.println("Could not listen on port: " + port);
        System.err.println(e);
        System.exit(1);
    }

    Socket client = null;
    while(true) {
        try {
            client = server.accept();
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.err.println(e);
            System.exit(1);
        }
        /* start a new thread to handle this client */
        Thread t = new Thread(new ClientConn(client));
        t.start();
    }
}

}


我现在明白了。我有两个out.close();.我删除了其中一个,它现在起作用了:)

1 个答案:

答案 0 :(得分:0)

目前,您只实现了套接字通信的一个方向。客户端当前仅发送数据,服务器仅接收数据。您想要的是在客户端上打开输入流,在服务器上打开输出流。在将命令发送到服务器之后,客户端将从输入流中读取,并且在从客户端读取命令之后服务器将写入输出流。与您当前实施的通信非常相似,但在另一个方向。