来自c程序的套接字向Python中的套接字发送3个数字。码和输出如下:为什么重复打印换行符?
蟒服务器代码:
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++客户端代码:
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;
服务器输出:
>>> 127.0.0.1 wrote:
12695
('127.0.0.1', 55624) did 12695 - 22695 on thread listen_th
28
496
8128
...然后连续换行符
clie nt输出:
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...
我假设C++客户端程序的最后一位就够了。同样假设它在服务器的while True
循环中。这两种语言都是新的,我知道我的代码还不好,请温柔......
我想如果没有什么受阻的recv()被读?我也认为选择封锁,直到有东西要读? – Marty 2012-03-16 13:27:29
@FrederickCraine如果连接已经关闭或者容易出错,那么可以读取“某些东西”,但是没有数据 - 只是必须修复的一个错误。你是对的'select.select'在被读取之前会阻塞,但是如果你发送的数据比你处理的要快,你最终会在你读的缓冲区中有多个“块”。 – 2012-03-16 13:29:23