套接字将3个数字发送到python中的套接字。代码和输出如下:
python服务器代码:
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
...然后连续换行
客户输出:
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
循环中的内容。对这两种语言都不熟悉,我知道我的编码还不好,温柔......
答案 0 :(得分:3)
这篇文章处理的内容比OP要求的要多一点,我为此事道歉。如果您只对如何修复服务器上写的待处理换行感兴趣,请跳转到“ python ”部分。
客户端/服务器
self.request.recv (...)
的来电中获得两个号码。<强>蟒强>
print
会在传递给它的每个语句后附加换行符('\n'
),除非您用逗号结束print
语句。
您应该添加一项检查以查看是否确实有任何数据需要读取,如果没有,则可能出现错误或连接已关闭。
while True:
select.select([self.rfile], [], [self.rfile])
self.data = self.request.recv(10)
if self.data:
print self.data
else:
# <close connection here>
<强> C ++ 强>
write(sock, perfect_numbers[i].c_str(), sizeof(perfect_numbers[i].c_str()))
无论sizeof(char*)
是一个还是十亿字节的长度,上面都会尝试将sock
个字符写入套接字perfect_numbers[i]
。
write
的第三个参数应该是您希望写入的字节数,因此您应该使用perfect_numbers[i].size ()
。 1
1 我认为您在查看以下示例时感到困惑:
char buf[1024];
...
write (sock, buf, sizeof (buf));
答案 1 :(得分:1)
对于流请求处理程序,self.request
是socket
对象。当套接字关闭时,socket.recv
函数返回一个空字符串。
答案 2 :(得分:1)
查看输出
我是0写作28
2 | 8 * | | *我...
我假设perfect_numbers [i]以\ n结尾(在这种情况下为“28 \ n”)。如何生成列表?