Pustaka soket C++ platform independen dengan dukungan SSL transparan (dan beberapa hal lainnya).
Dapatkan di sini: [Perpustakaan statis & bersama Windows x64 dengan dukungan SSL] atau [tanpa dukungan 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
};
Anda dapat mengganti socks::factory::makeThreadedServer
dengan socks::factory::makeMultiplexedServer
. Yang pertama membuat instance server yang membuat satu thread per klien (menggunakan I/O pemblokiran), yang kedua membuat instance server dengan arsitektur yang lebih skalabel, menggunakan pola reaktor (beberapa klien dilayani per thread menggunakan I/O non-pemblokiran).
# 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;
}
}
Anda juga dapat mengubah socks::DatagramSocket
menjadi soket datagram yang 'terhubung' dan menggunakan antarmuka socks::ClientSocket
.
socks::ClientSocket clientSocket = datagramSocket.makeClientSocket(peer);
/*
* from this point on 'datagramSocket' cannot be used anymore,
* its implementation has been moved to 'clientSocket'.
*/
atau
socks::ClientSocket clientSocket = datagramSocket.makeClientSocket(host, port); // same here
Ini adalah socks::ClientSocket
yang dibungkus dengan kelas std::iostream
.
# 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;
}
}
Ganti saja deklarasinya:
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<...>(...);
Itu saja. Untuk socks::ServerSocket
dan socks::Server
Anda juga memerlukan sertifikat dan file kunci (nama defaultnya adalah 'cert.pem' dan 'key.pem'). Untuk menghasilkan sertifikat pengujian dan file kunci:
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
Namespace ini berisi semua metode pabrik perpustakaan.
Contoh yang lebih rumit: implementasi server FTP yang sederhana namun berfungsi penuh menggunakan libsockets (termasuk dukungan SSL, mode pasif, resume & dukungan FXP). Panggilan balik autentikasi disediakan untuk pengguna. Anda juga dapat mendaftarkan perintah SITE khusus.
Anda dapat mencobanya: biner statis 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 ();
}
Segera hadir... (dalam pengembangan/pemfaktoran ulang, saat ini hanya berfungsi sebagai perpustakaan...)