-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Open
Description
Describe the bug
I have encountered an issue with my Android WebSocket server where it fails to correctly handle hexadecimal data sent from clients.
//java
//function
public byte[] hexStringToByteArray(String s) {
int len = s.length();
if (len % 2 != 0) {
throw new IllegalArgumentException("Hex string must have an even length");
}
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
@Override
public void onMessage(WebSocket conn, ByteBuffer message) {
//Log.d("websocket", "onMessage() Listen ByteBuffer data->"+ByteUtil.byteBufferToString(message));
byte[] bytes = new byte[message.remaining()];
message.get(bytes);
Log.d("websocket", "onMessage() Listen ByteBuffer data->"+byteArrayToHexString(bytes));
res.post(new Runnable() {
@Override
public void run() {
res.setText("Byte Listen:"+byteArrayToHexString(bytes));
}
});
}
//python socketClient
import asyncio
import websockets
async def send_byte_array():
uri = "ws://192.168.0.102:9093"
byte_data = bytes([0x02, 0x47, 0x00, 0xda, 0x5d, 0x4f, 0xf2, 0x02]) /// my byte
async with websockets.connect(uri) as websocket:
await websocket.send(byte_data)
print("Sent byte data:", byte_data.hex())
async def receive_byte_array():
uri = "ws://192.168.0.102:9093"
async with websockets.connect(uri) as websocket:
while True:
byte_data = await websocket.recv()
hex_string = byte_data.hex()
print("Received byte data:", hex_string)
async def main():
await asyncio.gather(send_byte_array(), receive_byte_array())
asyncio.get_event_loop().run_until_complete(main())
When running the Android WebSocket server and subsequently starting Python to send socket messages, the sent and received data do not match.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels
