【问题标题】:Android socket receive dataAndroid socket接收数据
【发布时间】:2015-07-31 22:20:31
【问题描述】:

我是 android 开发的新手,所以如果需要任何进一步的信息,请询问...我正在尝试使用套接字将坐标发送到服务器,接收查询结果并“Toast”它们。 到现在为止我的活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_socket);

    new Thread(new ClientThread()).start();     

}
      ...

 class ClientThread implements Runnable {
             @SuppressWarnings("deprecation")
            @Override
             public void run() {
                 try {
                     InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                     socket = new Socket(serverAddr, SERVERPORT);

                 } catch (UnknownHostException e1) {
                     e1.printStackTrace();
                 } catch (IOException e1) {
                     e1.printStackTrace();
                 }
             }
         }


      public void onClickk(View view) {
             try {
                // Acquire a reference to the system Location Manager
                LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);............here some more code regarding coordinates. ............

我正在通过套接字写入坐标(以相同的方法):

                        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

                        if (lat!=null){

                            String json = "";

                            // 3. build jsonObject
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.accumulate("lat", lat);
                                jsonObject.accumulate("lon", lon);
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            // 4. convert JSONObject to JSON to String
                            json = jsonObject.toString();

                         PrintWriter out = new PrintWriter(new BufferedWriter(
                                 new OutputStreamWriter(socket.getOutputStream())),
                                 true);
                         out.println(json);

如何接收服务器发送的数据?我不知道如何使用 InputSteam。

更新:我的服务器。当从应用程序接收到消息时,服务器会尝试在套接字上写入一个字符串。

       sock.on('data', function(data) {

          console.log('DATA ' + sock.remoteAddress + ': ' + data);

          sock.write(la);
       });

       });

【问题讨论】:

  • 服务器使用什么协议?除了http还有什么?
  • 我正在使用 java.net.Socket 库。希望这会有所帮助
  • 我不是说android app,你的服务器是java程序?
  • 不,这是一个expresse应用,nodejs
  • 你的代码很好,从套接字获取输入流,将其包装在像 datainputstream 这样的读取器中并读取传入的数据。

标签: android sockets inputstream


【解决方案1】:

我遇到了类似的问题,终于在这里找到了:

https://community.particle.io/t/using-tcp-to-communicate-between-an-android-and-photon-without-cloud-connection/28495/4

MainActivity.java

public class MainActivity extends AppCompatActivity {

    //    private ListView mList;
//    private ArrayList<String> arrayList;
//    private MyCustomAdapter mAdapter;
    private TCPClient mTcpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button button = (Button) findViewById(R.id.connectBtn);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // connect to the server
                TCPClient.buttonPushed = "Kamran Gasimov, hi";
                new connectTask().execute("");
            }
        });



    }

    public class connectTask extends AsyncTask<String,String,TCPClient> {

        @Override
        protected TCPClient doInBackground(String... message) {

            //we create a TCPClient object and
            mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
                @Override
                //here the messageReceived method is implemented
                public void messageReceived(String message) {
                    //this method calls the onProgressUpdate
                    publishProgress(message);
                    Log.d("Message", message);
                }
            });
            mTcpClient.run();

            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            Log.d("values", values[0]);
            //in the arrayList we add the messaged received from server
//            arrayList.add(values[0]);
            // notify the adapter that the data set has changed. This means that new message received
            // from server was added to the list
//            mAdapter.notifyDataSetChanged();
        }
    }
}

TCPClient.java

public class TCPClient {

    private String serverMessage;
    public static String buttonPushed;
    public static final String SERVERIP = "192.168.1.100"; //your Photon (formerly computer) IP address

    public static final int SERVERPORT = 7777;
    private OnMessageReceived mMessageListener = null;
    private boolean mRun = false;

    PrintWriter out;
    BufferedWriter out1;
    OutputStreamWriter out2;
    OutputStream out3;
    BufferedReader in;

    /**
     *  Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TCPClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     * @param message text entered by client
     */
    public void sendMessage(String message){
        if (out != null && !out.checkError()) {
            out.println(message);
            Log.d("TCP Client", "Message: " + message);
            out.flush();
        }
    }

    public void stopClient(){
        mRun = false;
    }

    public void run() {

        mRun = true;

        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(SERVERIP);

            Log.e("TCP Client", "C: Connecting...");

            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, SERVERPORT);

            try {
                //send the message to the server

                out3 = socket.getOutputStream();
                out2 = new OutputStreamWriter(socket.getOutputStream());
                out1 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                Log.e("TCP Client", "C: out3 = " + out3);
                Log.e("TCP Client", "C: out2 = " + out2);
                Log.e("TCP Client", "C: out1 = " + out1);
                Log.e("TCP Client", "C: out0 = " + out);

                sendMessage(buttonPushed); //this was the key
                Log.e("TCP Client", "C: Sent.");

                Log.e("TCP Client", "C: Done.");

                //receive the message which the server sends back
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                Log.e("TCP Client", "C: received = " + in);
                Log.e("TCP Client", "C: run = " + mRun);
                //in this while the client listens for the messages sent by the server
                while (mRun) {
                    Log.e("TCP Client", "C: I got to the while loop!");

                    serverMessage = in.readLine();

                    Log.e("TCP Client", "C: serverMessage = " + serverMessage);
                    new TCPClient(mMessageListener);
                    stopClient();
                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);
                    } else {
                        serverMessage = null;
                    }
                }

                Log.e("TCP Client", "C: run = " + mRun);

                Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
            } catch (Exception e) {
                Log.e("TCP", "S: Error", e);
            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
                socket.close();
                Log.d("TCP Client", "Socket closed.");
                serverMessage = null;
            }

        } catch (Exception e) {
            Log.e("TCP", "C: Error", e);
        }

    }

    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}

【讨论】:

    【解决方案2】:
    class Client extends Thread {
    
        public void run()
        {
             try
             {
                  Socket socket = new Socket(address, PORT);
                  PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                  out.println(json);
                  BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                  String response = in.readLine()
                  Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
                  socket.close();
             }
             catch(Exception e) {}
        }
    }
    

    【讨论】:

    • 阿里我似乎是正确的方式..但仍然没有收到 toast 通知
    • @gematzab 你收到数据了吗?你在服务器上发送吗?套接字编程非常棘手。当每一方都在不同的平台上时会更狡猾。
    • 我更新了问题。是的,我可以看到在节点服务器端接收到坐标。虽然我看不到是否从应用程序接收到数据。 (我也会将你的回复标记为答案,我认为这是正确的方法,即使我不能让它工作)
    • @gematzab 要让它工作,不要编写所有代码。它带来了很多混乱。我建议从像我这样的简单代码开始,它只发送一个数据字节并接收一个字节。在两边记录接收到的数据,这样你就可以确定一切都很好。
    猜你喜欢
    • 2014-08-29
    • 2020-01-09
    • 2013-11-01
    • 2021-07-30
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多