gpt4 book ai didi

c++ - SSL 读取和 SSL 同时写入

转载 作者:太空狗 更新时间:2023-10-29 21:43:57 25 4
gpt4 key购买 nike

我有两个线程,mainThreadrecvThread

recvThread 上,我调用了 SSL_read(ssl, readBuffer, sizeof(readBuffer))。这会阻塞线程,直到接收到数据。

然后,在 mainThread 上,我被告知需要发送一些数据。因此,我调用了 SSL_write(ssl, someData, sizeof(someData))

有时,这工作正常。其他时候,这会失败并出现奇怪的内部错误消息。我的猜测是,当在同一 ssl 上下文中发生 SSL_read 时,我无法调用 SSL_write。这对我来说很有意义,但我该如何解决呢?

我是否让 recvThread 做类似的事情:

SSL * ssl;
std::string data;
boost::mutex dataMutex;

while (recvThreadShouldBeRunning) {
char readBuffer[100];
auto nRead = SSL_read(ssl, readBuffer, sizeof(readBuffer)); //Non-blocking call to SSL_read.

// Do something with nRead (handle errors, use data)

{
auto dataLock = boost::unique_lock<boost::mutex>(dataMutex);
if (data.length() > 0)
{
SSL_write(ssl, data.c_str(), data.length());
}
}
sleep(50);
}

然后当我需要发送一些东西时...

{
auto dataLock = boost::unique_lock<boost::mutex>(dataMutex);
data = "some data";
}

这似乎可行,但我认为这对我的问题来说是一个相当丑陋的解决方案。有没有办法以某种方式SSL_lock() SSL_wait_on_data() SSL_unlock()?或者这是解决问题的最佳方法?

解决这类问题的标准方法是什么?

感谢您的宝贵时间。

最佳答案

文档中的引述似乎包含了答案:

OpenSSL can safely be used in multi-threaded applications provided that at least two callback functions are set, locking_function and threadid_func.

locking_function(int mode, int n, const char *file, int line) is needed to perform locking on shared data structures. (Note that OpenSSL uses a number of global data structures that will be implicitly shared whenever multiple threads use OpenSSL.) Multi-threaded applications will crash at random if it is not set.

locking_function() must be able to handle up to CRYPTO_num_locks() different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and releases it otherwise.

file and line are the file number of the function setting the lock. They can be useful for debugging.

-- threads - OpenSSL.

The example of using the locking-related functions (github) :

crypto/threads/mttest.c shows examples of the callback functions on Solaris, Irix and Win32.

-- threads - OpenSSL.

关于c++ - SSL 读取和 SSL 同时写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21527206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com