DP_S/include/SqrReg_Dio.hpp

63 lines
1.6 KiB
C++
Raw Normal View History

2024-10-23 19:53:15 +08:00
#pragma once
#include "squirrel.h"
#include "sqstdaux.h"
#include "sqstdblob.h"
#include "sqstdio.h"
#include "sqstdmath.h"
#include "sqstdstring.h"
#include "sqstdsystem.h"
#include <asio.hpp>
#include <asio/ssl.hpp>
#include <asio/basic_socket_streambuf.hpp>
#include <iostream>
static SQInteger CreateHttp(HSQUIRRELVM v)
{
const SQChar *Host;
sq_getstring(v, 2, &Host);
const SQChar *Sevice;
sq_getstring(v, 3, &Sevice);
const SQChar *Content;
sq_getstring(v, 4, &Content);
asio::io_context ioContext;
asio::ip::tcp::resolver resolver(ioContext);
asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(Host, Sevice);
asio::ip::tcp::socket socket(ioContext);
asio::connect(socket, endpoints);
std::string request = std::string(Content);
asio::write(socket, asio::buffer(request));
asio::streambuf response;
asio::error_code error;
asio::read(socket, response, error);
if (error != asio::error::eof)
{
throw asio::system_error(error);
sq_pushnull(v);
}
std::istream responseStream(&response);
std::ostringstream oss;
oss << responseStream.rdbuf();
sq_pushstring(v, oss.str().c_str(), -1);
return 1;
}
static SQInteger register_Dio_func(HSQUIRRELVM v, SQFUNCTION f, const char *fname)
{
sq_pushroottable(v);
sq_pushstring(v, fname, -1);
sq_newclosure(v, f, 0); // create a new function
sq_newslot(v, -3, SQFalse);
sq_pop(v, 1); // pops the root table
}
static void RegisterDio(HSQUIRRELVM v)
{
// 创建Http
register_Dio_func(v, CreateHttp, _SC("Sq_CreateHttp"));
}