socket from c program sends 3 numbers to a socket in python. code and output below:
python server code:
import SocketServer
import threading
import select
import sys
class TCPHandler(SocketServer.StreamRequestHandler):
def handle(self):
self.data = self.rfile.readline()
print "%s wrote:" % self.client_address[0]
print (self.data)
self.request.send(str(long(self.data)+1000))
cur_connex.append({'ip': self.client_address, 'range': [long(self.data), long(self.data)+10000]})
for a in cur_connex:
print("%s did %d - %d on thread %s" % (a['ip'], a['range'][0], a['range'][1], threading.current_thread().name))
while True:
select.select([self.rfile], [], [])
self.data = self.request.recv(10) #also tried "self.data = self.rfile.readline().strip("\n")" and without "strip()"
print self.data
if __name__ == "__main__":
HOST, PORT = "", 50001
cur_connex = []
done_up_to = 0
# Create the server, binding to localhost on port 50001
server = SocketServer.TCPServer((HOST, PORT), TCPHandler)
# Activate the server on new thread
listen_thread = threading.Thread(target=server.serve_forever, name='listen_th')
listen_thread.start()
c++ client code:
for(unsigned long long i; i < perfect_numbers.size(); i++)
{
cout << "i is " << i << " writing " << perfect_numbers[i] << "\n";
for(int j = 0; j < perfect_numbers[i].size(); j++)
{
cout << perfect_numbers[i][j] << "|";
}
if(write(sock, perfect_numbers[i].c_str(), sizeof(perfect_numbers[i].c_str())) == -1)
{
cerr << "\nwrite failed: " << strerror(errno) << "\n";
return -1;
}
}
if(close(sock) == -1)
{
cerr << "close sock error: " << strerror(errno) << "\n";
return -1;
}
cout << "exiting...\n";
return 1;
server output:
>>> 127.0.0.1 wrote:
12695
('127.0.0.1', 55624) did 12695 - 22695 on thread listen_th
28
496
8128
…and then continuous newlines
client output:
that took 1.26624 seconds
i is 0 writing 28
2|8|
|i is 1 writing 496
4|9|6|
|i is 2 writing 8128
8|1|2|8|
|exiting...
I assume that last bit of the C++ client program is enough. Also assuming it’s something in that while True loop in the server. New to both these languages, I know my coding isn’t good yet, be gentle…
this post handles a bit more than what OP was asking for, I apologize for this matter. If you are only interested in how to fix the pending newlines written at the server please jump to section “python“.
both client/server
self.request.recv (...).python
printwill append a newline ('\n') to every statement passed to it, unless you end theprintstatement with a comma.You should add a check to see if there really was any data to be read, if not there might have been an error or the connection has been closed.
c++
The above will always try to write
sizeof(char*)characters to the socketsock, no matter ifperfect_numbers[i]is one or a billion bytes of length.The third argument to
writeshould be the number of bytes that you wish to be written, therefore you should useperfect_numbers[i].size (). 11 I assume that you’ve been confused when looking at examples such as: