C ++ Server使用TCP向Android客户端发送消息

时间:2015-04-07 16:03:51

标签: android c++ sockets

问题

我正在尝试将数据包从C ++服务器发送到我的Android客户端,但是android客户端永远不会收到数据包。我在android上尝试了不同的东西,包括readline和read buffer,但是这些东西永远不会返回任何东西。此外,我正在调用方法从主活动页面接收数据包。

C ++代码

int numBytes;  // the number of bytes sent

// Sends the message to the connected host
try 
{
    string sendMsg = "This is a test \r\n";

    if (numBytes = send(socketId, sendMsg.c_str(), sendMsg.size(), 0) == -1)
    {

            int errorCode = 0;
            string errorMsg = "error calling send():\n";
            detectErrorSend(&errorCode,errorMsg);
            CExceptionEx socketSendException(errorCode,errorMsg);
            throw socketSendException;
    }
}
catch(CExceptionEx& excp)
{
    excp.response();
    exit(1);
}

return numBytes;

Android代码

public void RecievePacket()
{
    try 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(mSock.getInputStream()));
        String test = br.readLine();

       /* BufferedInputStream input = new BufferedInputStream(mSock.getInputStream());
        byte[] buffer = new byte[10]; // 10 bytes buffer
        int bytesRead = 0;
        while( (bytesRead=input.read(buffer)) !=-1 ) { // read up to 10 bytes
            String str = new String(buffer,0,bytesRead); // convert bytes to String using default encoding
            //System.out.println("Data received: " + str);

        }
        */


    }
    catch (Exception ex)
    {
    }

}

注意

注释的代码块是我尝试接收消息的另一种方式,请注意我能够将数据包从Android发送到C ++。

修改

send()发送0个字节但是我能够从android接收数据包所以必须有连接。

2 个答案:

答案 0 :(得分:2)

一定有什么不对的,这不是你给我们的代码的一部分。我使用您的代码在我自己的计算机上编写了自己的最小示例,一切都按预期工作。检查这是否在您的计算机上正确运行(运行C ++,然后运行Java)。还要检查我的C ++代码中是否有任何您缺少的内容。

socket.cpp :(我更像是一个C程序员,所以我只是用C ++代替你提供的代码。)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <string>

void connection(int sock)
{
  // Pretty much your C++ code verbatim.
  std::string sendMsg = "This is a test \r\n";
  int amt = send(sock, sendMsg.c_str(), sendMsg.size(), 0);
  printf("Send %d bytes.\n", amt);
  close(sock);
}

int main(int argc, char *argv[])
{
  int sock, csock;
  struct sockaddr_in sin;
  char *host = "127.0.0.1";
  unsigned short port = 1234;

  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(EXIT_FAILURE);
  }

  sin.sin_family = AF_INET;
  sin.sin_port = htons(port);
  if (inet_pton(AF_INET, host, &sin.sin_addr) != 1) {
    perror("inet_pton");
    exit(EXIT_FAILURE);
  }

  if (bind(sock, (struct sockaddr*) &sin, sizeof(sin)) != 0) {
    perror("bind");
    exit(EXIT_FAILURE);
  }

  if (listen(sock, SOMAXCONN) != 0) {
    perror("listen");
    exit(EXIT_FAILURE);
  }

  if ((csock = accept(sock, NULL, NULL)) == -1) {
    perror("accept");
    exit(EXIT_FAILURE);
  }

  connection(csock);
  close(sock);
  return EXIT_SUCCESS;
}

SockTest.java:

import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SockTest {
    public static void main(String[] args) {
        try {
            Socket sock = new Socket("127.0.0.1", 1234);

            // Your Java Code Verbatim:
            BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            String test = br.readLine();

            System.out.println(test);
            sock.close();
        } catch (Exception ex) {}
    }
}

C ++的输出:

$ ./socket
Send 17 bytes.

Java的输出:

$ java SockTest
This is a test 

答案 1 :(得分:0)

不应该

 if (numBytes = send(socketId, sendMsg.c_str(), (sendMsg.size() + 1), 0) == -1) ...

请注意 +1