客户端如何等待可能的服务器消息?

时间:2012-11-22 13:44:14

标签: android sockets client inputstream

我是新手,所以如果我提出愚蠢的问题,我很抱歉。
我必须与服务器进行套接字连接 客户端(Android设备)必须向服务器发送消息并等待确认消息。然后,如果服务器在30秒内没有从客户端收到任何内容,则发送请求ack消息 我所做的就是第一部分:客户端发送消息并阅读响应 我要问的是:客户端如何等待来自服务器的可能消息? 这是我写的代码:
在onCreate方法中:

Thread myThread = new Thread(new myRunnable());
myThread.start();

这是myRunnable:

public class myRunnable implements Runnable{
  public void run(){
    try{
      Socket socket = new Socket(serverIp, serverPort);
      InputStream is = socket.getInputStream();
      OutputStream out = socket.getOutputStream();
      out.write(byteBuffer.array());
      out.flush();
      byte[] bbb = new byte[1024];
      // Receive message from server
      int bytesToRead= is.read(bbb);
      is.close();
      out.close();
      socket.close();

Successives读取操作返回-1,那么如何等待服务器消息呢? 非常感谢您的任何建议。

1 个答案:

答案 0 :(得分:4)

你不应该关闭溪流。关闭流时,您与服务器的通信将关闭。通常服务器通信在无限循环中发生。像这样:

public class myRunnable implements Runnable{
  public void run(){
    try{
      Socket socket = new Socket(serverIp, serverPort);
      InputStream is = socket.getInputStream();
      OutputStream out = socket.getOutputStream();
      out.write(byteBuffer.array());
      out.flush();
      byte[] bbb = new byte[1024];
      while (true) {
         // Read next message.
         bytesToRead = is.read(bbb);
         // handle message...
         // If you need to stop communication use 'break' to exit loop;
      }
      is.close();
      out.close();
      socket.close();

所以线程在第bytesToRead = is.read(bbb)行停止,直到服务器发送任何消息,然后它以任何你想要的方式处理消息并返回阅读下一条消息。如果您需要使用break停止通信退出循环。