libsockets
1.0.0
一个独立于平台的 C++ 套接字库,具有透明的 SSL 支持(以及更多内容)。
在此处获取:[支持 SSL 的 Windows x64 静态和共享库] 或 [不支持 SSL]
# include " libsockets.h "
void client () {
socks::ClientSocket clientSocket;
if (clientSocket. connectTo ( " 127.0.0.1 " , " 10000 " ) == 0 ) {
std::string hello = " Hello World " ;
clientSocket. sendData (hello. c_str (), hello. size ());
}
};
int main () {
client ();
};
# include " libsockets.h "
void server () {
socks::ServerSocket serverSocket;
serverSocket. listenForConnections ( " 127.0.0.1 " , " 10000 " );
socks::ClientSocket clientSocket = serverSocket. acceptConnection ();
char buf[ 512 ];
auto len = clientSocket. receiveData (buf, 512 );
if (len > 0 ) {
buf[len]= 0 ;
std::cout << buf << std::endl;
}
};
int main () {
server ();
};
$ > ./server &
$ > ./client
socks::makeThreaded[SSL]Server
和socks::makeMultiplexed[SSL]Server
) # include " libsockets.h "
class MyContext {
public:
int value; // whatever context you need to maintain
};
void onReceive (socks::Context<MyContext> &context, std::istream &inp, std::ostream &outp) {
std::string word;
while (inp >> word)
outp << context. getContext (). value ++ << " " << word << std::endl;
};
void onConnect (socks::Context<MyContext> &context, std::istream &inp, std::ostream &outp) {
context. getContext (). value = 0 ;
outp << " Hello " << std::endl;
};
int main () {
auto myServer = socks::factory::makeThreadedServer<MyContext>(
onReceive,
onConnect /* ,
onDisconnect,
afterWrite
*/
); // onReceive is mandatory, onConnect, onDisconnect & afterWrite are optional
myServer. listen ( " 127.0.0.1 " , " 10000 " ); // serves
};
您可以将socks::factory::makeThreadedServer
替换为socks::factory::makeMultiplexedServer
。第一个实例化一个服务器,为每个客户端创建一个线程(使用阻塞 I/O),第二个实例化一个服务器,该服务器具有更具可扩展性的架构,使用反应器模式(使用非阻塞 I/O,每个线程为多个客户端提供服务)。
# include " libsockets.h "
constexpr size_t bufferSize = 4096 ;
int main () {
socks::DatagramSocket datagramSocket;
datagramSocket. bindSocket ( " 0.0.0.0 " , " 10000 " );
char buffer[bufferSize];
std::pair< int , socks::SocketAddress> ret = datagramSocket. receiveFrom (buffer, bufferSize);
// ret = pair<bytes received, sender address>
if (ret. first > 0 ) {
auto peer = std::move (ret. second );
std::string reply = " received " + std::to_string (ret. first ) + " bytes " ;
datagramSocket. sendTo (peer, reply. c_str (), reply. size ());
} else {
std::cerr << " error receiving. " << std::endl;
}
}
您还可以将socks::DatagramSocket
转换为“已连接”数据报套接字并使用socks::ClientSocket
的接口。
socks::ClientSocket clientSocket = datagramSocket.makeClientSocket(peer);
/*
* from this point on 'datagramSocket' cannot be used anymore,
* its implementation has been moved to 'clientSocket'.
*/
或者
socks::ClientSocket clientSocket = datagramSocket.makeClientSocket(host, port); // same here
它是一个封装在std::iostream
类中的socks::ClientSocket
。
# include " libsockets.h "
int main () {
socks::SocketStream socketStream;
if (socketStream. connectTo ( " 127.0.0.1 " , " 10000 " ) == 0 ) {
std::string buf;
std::getline (socketStream, buf); // receiving data
std::cout << buf << std::endl;
socketStream << " message received. " << std::endl; // transmitting data
} else {
std::cerr << " error connecting. " << std::endl;
}
}
只需替换声明:
socks::ClientSocket clientSocket = socks::factory::makeSSLClientSocket;
socks::ServerSocket serverSocket = socks::factory::makeSSLServerSocket;
socks::SocketStream socketStream = socks::factory::makeSSLSocketStream;
socks::Server server = socks::factory::makeThreadedSSLServer<...>(...);
socks::Server server = socks::factory::makeMultiplexedSSLServer<...>(...);
就是这样。对于socks::ServerSocket
和socks::Server
您还需要证书和密钥文件(默认名称为“cert.pem”和“key.pem”)。生成测试证书和密钥文件:
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
该命名空间包含所有库的工厂方法。
一个更详细的示例:使用 libsockets 的简单但功能齐全的 FTP 服务器实现(包括 SSL 支持、被动模式、恢复和 FXP 支持)。为用户提供身份验证回调。您还可以注册自定义 SITE 命令。
您可以尝试一下:Windows x64 静态二进制文件
AuthenticationFunction FTPClientInfo::authenticate =
[]( const std::string &username, const std::string &password, FTPClientInfo& clientInfo) {
/*
* in here a user profile can be loaded into 'clientInfo'
* upon authentication in order to define, for example,
* a home dir, chroot, etc.
*/
return authService. authenticate (username, password);
};
int main ( int argc, char **argv) {
FTPServer ftpServer;
// SITE CLIENT COUNT
ftpServer. registerSiteCommand (
" CLIENT " ,
[&ftpServer]( const std::string ¶ms, FTPClientInfo &clientInfo) {
std::stringstream ss (params);
std::string p1;
ss >> p1;
std::transform (p1. begin (), p1. end (), p1. begin (), ::toupper);
if (p1 == " COUNT " )
return " 200 There is/are " + std::to_string (ftpServer. getClientCount ()) + " client(s) online. " ;
else
return std::string ( " 501 Invalid SITE CLIENT parameter. " );
});
ftpServer. start ();
}
即将推出...(正在开发/重构中,目前仅作为库使用...)