将代码从 Python 转换为 C++ 时出错

Error translating code from Python to C ++

本文关键字:C++ 出错 转换 代码 Python      更新时间:2023-10-16

我试着从Python唱这段代码到C++:

import socket
host, port, length = '127.0.0.1', 3000, 8
sock = socket.create_connection((host, port))
sock.send(b'x02x01x00x00x00x00x006buildneditionnnodenservicenservicesnstatisticsnversion')
buf = bytearray(length)
buf = bytearray(length)
view = memoryview(buf)
while length > 0:
nbytes = sock.recv_into(view, length)
view = view[nbytes:]
length -= nbytes
print(buf)

二手boost::asio::ip::tcp::socket.以下是负责发送请求和接收响应的代码部分:

boost::asio::io_service service;
boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 3000);
boost::asio::ip::tcp::socket sock(service);
sock.open(boost::asio::ip::tcp::v4());
sock.connect(ep);
sock.write_some(boost::asio::buffer("x02x01x00x00x00x00x006buildneditionnnodenservicenservicesnstatisticsnversion"));
char buff[1024];
sock.read_some(boost::asio::buffer(buff,1024));
sock.shutdown(boost::asio::ip::tcp::socket::shutdown_receive);
sock.close();
std::cout << buff;

但是,此代码在收到响应时冻结(执行sock.read_some()时(。这里可以更改/更正什么?

我编译了您的C++客户端,只是稍微改变了它。

#include <iostream>
#include <boost/asio.hpp>
int main(int, char**) {
boost::asio::io_service service;
boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 3000);
boost::asio::ip::tcp::socket sock(service);
sock.open(boost::asio::ip::tcp::v4());
sock.connect(ep);
sock.write_some(boost::asio::buffer("the test message"));
char buff[1024];
auto rcvd_bytes = sock.read_some(boost::asio::buffer(buff,1024));
std::cout << "rcvd_bytes:" << rcvd_bytes << 'n';
sock.shutdown(boost::asio::ip::tcp::socket::shutdown_receive);
sock.close();
std::cout << buff << 'n';
}

我得到套接字服务器。TCPServer 示例

import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 3000
# Create the server, binding to localhost on port 9999
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()

我启动了这两个应用程序,一切似乎都正常。

服务器

127.0.0.1 wrote:
b'the test messagex00'

客户

rcvd_bytes:17
THE TEST MESSAGE

恐怕没有真实的服务器代码和相应的环境,很难理解什么在您的情况下不起作用。