[英]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. 我在C端有一个SSL函数,该函数仅接收发送的确切字节数。 Problem is that I'm sending strings & JSON of different byte length's from my servlet.
问题是我正在从servlet发送具有不同字节长度的字符串和JSON。
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. 在C端:我首先读取传入字节长度的传入字节,然后再次调用该函数以期望该消息。 Now, my Json is 349 while the other requests are 12. These are 3 and 2 bytes respectively.
现在,我的Json是349,而其他请求是12。这些分别是3和2个字节。
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. 当前解决方案:我在2个字节的请求中添加了一个零,以使它们变为3个字节。 Any smarter way of doing this?
有更聪明的方法吗?
Going by what Serge and Drew suggested I was to able to do this using Binary method. 按照Serge和Drew的建议,我可以使用Binary方法做到这一点。 Here's how I'm sending the string in Binary format:
这是我以二进制格式发送字符串的方法:
String user_length = String.format("%9s",
Integer.toBinaryString(all_Users.length()).replace(' ', '0'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.