Android应用程序通过套接字与Android本机二进制文件交谈

时间:2012-06-06 08:34:22

标签: android c sockets

我正在尝试通过套接字让Android客户端应用与Android本机二进制服务器通信。

我的应用程序有一个按钮,当按下该按钮时,会将用户输入的文本发送到服务器。代码如下:

Button.OnClickListener buttonSendOnClickListener = new Button.OnClickListener(){
  public void onClick(View arg0) {
    Socket socket = null;
    DataOutputStream dataOutputStream = null;
    DataInputStream dataInputStream = null;

    try {
      socket = new Socket("10.0.2.2", 20002);
      dataOutputStream = new DataOutputStream(socket.getOutputStream());
      dataInputStream = new DataInputStream(socket.getInputStream());
      dataOutputStream.writeUTF(textOut.getText().toString());
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    finally{
      if (socket != null){
      try {
        socket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    if (dataOutputStream != null){
      try {
        dataOutputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    if (dataInputStream != null){
     try {
        dataInputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}};

我的服务器是用C语言编写的,并且交叉编译为ARM二进制文件。代码如下:

int main(int argc, char ** argv)
{
  int sockfd, newsockfd, portno;
  socklen_t clilen;
  char buffer[256];
  struct sockaddr_in serv_addr, cli_addr;
  int n;

  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) 
    error("ERROR opening socket");

  // Initialize socket structure
  bzero((char *) &serv_addr, sizeof(serv_addr));
  portno = 20002;
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(portno);

  if (bind(sockfd, (struct sockaddr *) &serv_addr,
    sizeof(serv_addr)) < 0) 
    error("ERROR on binding");
  listen(sockfd,5);
  clilen = sizeof(cli_addr);
  newsockfd = accept(sockfd, 
     (struct sockaddr *) &cli_addr, 
     &clilen);
  if (newsockfd < 0) 
    error("ERROR on accept");
  bzero(buffer,256);
  n = read(newsockfd,buffer,255);
  if (n < 0) error("ERROR reading from socket");
  printf("Here is the message: %s\n",buffer);
  n = write(newsockfd,"I got your message",18);
  if (n < 0) error("ERROR writing to socket");
  close(newsockfd);
  close(sockfd);
  return 0;
}

我使用adb shell运行服务器,它运行直到accept()调用,等待它们进行连接。然后我运行客户端应用程序,然后点击发送按钮。但是,它似乎没有发送任何东西。我有什么问题吗?例如localhost的IP地址错误,或使用AF_INET而不是PF_UNIX或什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

如果您的客户端与服务器位于同一设备上,请尝试更改

socket = new Socket("10.0.2.2", 20002);

by:

socket = new Socket("127.0.0.1", 20002);