Search code examples
javaandroidc++socketswinsock

NUL values in the first character in receive function of sockets in c++ while sending data from android client


I need to transfer data from android client to c++ server using sockets and using this code.

I am sending "ACK" from Android client and reeving NUL pointer in the Server C++ and then the" ACK". Receiving message[512] is representing like this:

Data :

messageString[0]= NUL
messageString[1]= A; 
messageString[2]= C; 
messageString[3]= K;

ACIII Values :

messageString[0]= 0 
messageString[1]= 65; 
messageString[2]= 67; 
messageString[3]= 75;

Why am i receiving NUL in the receive in the c++ side.

As i am debugging and have realized that when i receive a message second time it is coming correct. But for the first time NUL is there for every new type of message.

Error Image:

https://drive.google.com/file/d/0B9Oz1-JlgLdTVVR6UUc4TGZtU2s/view?pli=1

Receive function on C++ server:

char messageString[512];
int result = recv(socket, messageString, strlen(messageString), 0);

Send in Andorid client :

public class AgentOutputChannel
{
    Socket clientSocket = null;
    OutputStream socketOutputStream = null;

    static  AgentOutputChannel outputChannel = null;

    private AgentOutputChannel()
    {       

    }

    private AgentOutputChannel(Socket socket, OutputStream outStream)
    {
        clientSocket = socket;
        socketOutputStream = outStream;
    }

    public  static AgentOutputChannel GetOutputChannel(Socket socket, OutputStream outStream)
    {
        if(outputChannel == null)
        {
            outputChannel = new AgentOutputChannel(socket, outStream);
        }
        return outputChannel;
    }

    public void Send(byte[] message)
    {
        try 
        {
            if(!clientSocket.isOutputShutdown())
            {
                socketOutputStream.write(message);
            }
            else
            {
                outputChannel = null;
            }
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Solution

  • int result = recv(socket, messageString, strlen(messageString), 0);
    

    should instead read

    int result = recv(socket, messageString, sizeof(messageString), 0);
    

    Also try printing the values of each byte of message right before

    socketOutputStream.write(message);
    

    to make sure that you aren't transmitting the null, ACK