4

Problem

I am trying to send a packet from C++ Server to my Android client but the android client is never receiving the packet. I have tried different things on android both the readline and read buffer but these never return anything. Also I am calling the Method to receive packet from the main activity page.

C++ Code

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 Code

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)
    {
    }

}

Note

The commented code block is the the other way I tried to receive the message, also please note that I am able to send packets from Android to C++.

Edit

The send() is sending 0 bytes but i am able to receive packets from android so there must be a connection.

11
  • You're using "\r \n" with a space in between them. I don't think that's the cause of any problems, but it's probably not what you want to be doing. Commented Apr 7, 2015 at 16:08
  • Also, send() returns the number of bytes sent, or -1 on error. It might be useful to print out the return value so you can see whether it actually sent everything. Commented Apr 7, 2015 at 16:11
  • Have you verified that the C++ server is reachable from the android device? I recommend using some sort of ping tool. Commented Apr 7, 2015 at 16:12
  • I am able to connect and send message from the Android client and they are being received by C++ server so i think it is reachable. Commented Apr 7, 2015 at 16:14
  • In your C++ code, socketID isn't your server socket, is it? Commented Apr 7, 2015 at 16:22

2 Answers 2

2

There must be something wrong that's not part of the code you've given us. I wrote my own minimal example running on my own computer using your code, and everything worked as expected. Check if this runs correctly on your computer (run the C++, then the Java). Also check if there's anything I do in my C++ code that you're missing.

socket.cpp: (I'm more of a C programmer, so I just used C++ for the code you provided).

#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) {}
    }
}

Output for the C++:

$ ./socket
Send 17 bytes.

Output for the Java:

$ java SockTest
This is a test 
Sign up to request clarification or add additional context in comments.

3 Comments

If this works on your computer, the next step is to try running the Java code (with a modified Socket address, of course) on your Android device. This is a very useful way to debug: reduce to the bare minimum to see if you can reproduce it, then start adding in complexity till you find the issue.
Ok this worked on my android i am going to check to see what i am doing wrong on my implementation.
I have this exact same problem, and your code works for me as well, however, if I don't close(sock); after sending the data, the problem remains. Any ideas?
0

shouldn't it be

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

Note that +1

1 Comment

The +1 won't fix anything -- it will just tell send to include the null-terminating byte. Generally, null-terminators aren't sent through sockets. Messages are usually separated by things like "\r\n", or they will have a predefined length.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.