简体   繁体   中英

Sending bytes over socket (Java Servlet to C)

I have an SSL function on my C side that receives only the exact number of bytes sent. Problem is that I'm sending strings & JSON of different byte length's from my servlet.

My Approach: I'm sending the length of each string first then the actual message.

         //For Json String (349 bytes)

            outputstreamwriter.write(jsonLength);
            outputstreamwriter.write(jsonData);
            outputstreamwriter.flush();

    // For other request strings

    final String path = request.getPathInfo();

    String all_Users = "GET ALL USERS";
    String user_length = Integer.toString(all_Users.length());

    String all_Keys = "GET ALL KEYS";
    String key_length = Integer.toString(all_Keys.length());

    if (path == null || path.endsWith("/users")) 
    {       outputstreamwriter.write(user_length);  
            outputstreamwriter.write(all_Users);    

    } 
    else if (path.endsWith("/keys")) {
        outputstreamwriter.write(key_length);
        outputstreamwriter.write(all_Keys); 
    } 

On the C side: I first read the incoming bytes for the incoming string length and then call the function again to expect that message. Now, my Json is 349 while the other requests are 12. These are 3 and 2 bytes respectively.

  debug_print("Clearing Buffer\n", NULL);
  memset(inBuf, 0, 1024);

  ssl_recv_exactly(rs_ssl, inBuf, 2, &ssllog))

  lengthValue = atoi(inBuf);
  printf("successfully received %d bytes of request:\n<%s>\n", lengthValue, inBuf);
             }

        if (lengthValue == 13)
        {
         // Call this function


        else if (lengthValue == 12)
                {
                     // call this function
                              }

Current solution: I'm adding a zero to my 2 byte requests to make them 3 bytes. Any smarter way of doing this?

Going by what Serge and Drew suggested I was to able to do this using Binary method. Here's how I'm sending the string in Binary format:

    String user_length = String.format("%9s", 
    Integer.toBinaryString(all_Users.length()).replace(' ', '0'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM