I wrote a custom Python client and server that communicate through TCP sockets:
- Client connects to the server
- Client sits idle until server sends a custom command to the client (for example, server sends the amount of seconds it wants the client to sleep)
- Client executes the command (something like time.sleep(5))
- Client sends a response back to the server once the command is finished executing
- Go to Step 2 and repeat
The way I send and receive socket data is as follows:
- Create a message that is a JSON string
- Read/Write a message length to socket (when reading, client/server will freeze until the message is received, which is OK for my use case)
- Read/Write a message to socket (since the length is known, we know how many bytes we need to read from the socket to get the whole message)
I tried writing the server using Node.JS and keeping the client in Python (I have no JS experience):
var net = require('net');
var server = net.createServer(function(socket) {
console.log('Connected:', socket.remoteAddress, ':', socket.remotePort);
while (true) {
// Send a custom command to the client
values = prepareMessage({ 'command' : 'sleep', 'time' : '5' })
socket.write(values[0]);
socket.write(values[1]);
// Wait for client to execute the command and receive response
res = socket.read(32); // Message length is at most 32 bits
while(res == null) {
res = socket.read(32);
console.log('Wait for message length');
}
console.log('Message length received, now read message');
message = socket.read(res);
}
});
server.listen(1337, '127.0.0.1');
/*
Converts message from dictionary to a correct format to pass onto the client
*/
function prepareMessage(msg) {
var message = JSON.stringify(msg);
var message_length = (message.length).toString(2);
// Make the message contain 32 bits
while(message_length.length < 32) {
message_length = "0" + message_length;
}
return [message_length, message];
}
Problem is, my socket.read()
method is constantly returning null
, no matter what I send to it. Is there a way to convert my python server code to this?